Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to plot events on time on using matplotlib

I have 3 lists, each containing numbers, representing a time. The time represents occuring of an event. For example, in this A, I have a number for each occurence of event A. I want to represent this data on a graph. In either of the following two ways:

1)

aabaaabbccacac

2)

a-> xx xxx    x x
b->   x   xx  
c->         xx x x
like image 258
yasar Avatar asked Jan 07 '12 19:01

yasar


People also ask

How do you plot time data in Python?

In X-axis we should have a variable of DateTime. In Y-axis we can have the variable which we want to analyze with respect to time. plt. plot() method is used to plot the graph in matplotlib.

Can matplotlib plot real time graphs?

To create a real-time plot, we need to use the animation module in matplotlib. We set up the figure and axes in the usual way, but we draw directly to the axes, ax , when we want to create a new frame in the animation.


1 Answers

You could use plt.hlines:

import matplotlib.pyplot as plt
import random
import numpy as np
import string

def generate_data(N = 20):
    data = [random.randrange(3) for x in range(N)]
    A = [i for i, x in enumerate(data) if x == 0]
    B = [i for i, x in enumerate(data) if x == 1]
    C = [i for i, x in enumerate(data) if x == 2]
    return A,B,C

def to_xy(*events):
    x, y = [], []
    for i,event in enumerate(events):
        y.extend([i]*len(event))
        x.extend(event)
    x, y = np.array(x), np.array(y)
    return x,y

def event_string(x,y):
    labels = np.array(list(string.uppercase))        
    seq = labels[y[np.argsort(x)]]
    return seq.tostring()

def plot_events(x,y):
    labels = np.array(list(string.uppercase))    
    plt.hlines(y, x, x+1, lw = 2, color = 'red')
    plt.ylim(max(y)+0.5, min(y)-0.5)
    plt.yticks(range(y.max()+1), labels)
    plt.show()

A,B,C = generate_data(20)
x,y = to_xy(A,B,C)
print(event_string(x,y))
plot_events(x,y)

yields

BBACBCACCABACCBCABCC

enter image description here

like image 134
unutbu Avatar answered Oct 13 '22 22:10

unutbu