如何使用matplotlib按时绘制事件

2024-05-23 18:45:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我有3个列表,每个包含数字,代表一个时间。时间表示事件的发生。例如,在这个A中,每次发生事件A我都有一个数字。我想用图表来表示这些数据。以以下两种方式之一:

(一)

aabaaabbccacac

2个)

a-> xx xxx    x x
b->   x   xx  
c->         xx x x

Tags: 数据列表方式时间事件代表用图表数字
3条回答

您可以使用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)

收益率

BBACBCACCABACCBCABCC

enter image description here

作为前面答案的扩展,您可以使用plt.hbar

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

x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13])
y = np.array([0, 0, 1, 0, 0, 0, 1, 1, 2, 2, 0, 2, 0, 2])

labels = np.array(list(string.uppercase))    
plt.barh(y, [1]*len(x), left=x, color = 'red', edgecolor = 'red', align='center', height=1)
plt.ylim(max(y)+0.5, min(y)-0.5)
plt.yticks(np.arange(y.max()+1), labels)
plt.show()

enter image description here

或者,你可以试试这样的事情:

import matplotlib.pyplot as plt
import numpy as np

data = [[1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0],
        [0, 0, 2, 0, 0, 0, 2, 2, 0, 0, 0, 0, 0, 0], 
        [0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 0, 3, 0, 3]]

fig = plt.figure()
ax = fig.add_subplot(111)
ax.axes.get_yaxis().set_visible(False)
ax.set_aspect(1)

def avg(a, b):
    return (a + b) / 2.0

for y, row in enumerate(data):
    for x, col in enumerate(row):
        x1 = [x, x+1]
        y1 = np.array([y, y])
        y2 = y1+1
        if col == 1:
            plt.fill_between(x1, y1, y2=y2, color='red')
            plt.text(avg(x1[0], x1[1]), avg(y1[0], y2[0]), "A", 
                                        horizontalalignment='center',
                                        verticalalignment='center')
        if col == 2:
            plt.fill_between(x1, y1, y2=y2, color='orange')
            plt.text(avg(x1[0], x1[0]+1), avg(y1[0], y2[0]), "B", 
                                        horizontalalignment='center',
                                        verticalalignment='center')
        if col == 3:
            plt.fill_between(x1, y1, y2=y2, color='yellow')
            plt.text(avg(x1[0], x1[0]+1), avg(y1[0], y2[0]), "C", 
                                        horizontalalignment='center',
                                        verticalalignment='center')

plt.ylim(3, 0)
plt.show()

enter image description here

如果希望所有插槽位于同一行,只需进行一些更改,如下所示:

import matplotlib.pyplot as plt
import numpy as np

data = [[1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0],
        [0, 0, 2, 0, 0, 0, 2, 2, 0, 0, 0, 0, 0, 0], 
        [0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 0, 3, 0, 3]]

fig = plt.figure()
ax = fig.add_subplot(111)
ax.axes.get_yaxis().set_visible(False)
ax.set_aspect(1)

def avg(a, b):
    return (a + b) / 2.0

for y, row in enumerate(data):
    for x, col in enumerate(row):
        x1 = [x, x+1]
        y1 = [0, 0]
        y2 = [1, 1]
        if col == 1:
            plt.fill_between(x1, y1, y2=y2, color='red')
            plt.text(avg(x1[0], x1[1]), avg(y1[0], y2[0]), "A", 
                                        horizontalalignment='center',
                                        verticalalignment='center')
        if col == 2:
            plt.fill_between(x1, y1, y2=y2, color='orange')
            plt.text(avg(x1[0], x1[0]+1), avg(y1[0], y2[0]), "B", 
                                        horizontalalignment='center',
                                        verticalalignment='center')
        if col == 3:
            plt.fill_between(x1, y1, y2=y2, color='yellow')
            plt.text(avg(x1[0], x1[0]+1), avg(y1[0], y2[0]), "C", 
                                        horizontalalignment='center',
                                        verticalalignment='center')

plt.ylim(1, 0)
plt.show()

enter image description here

第二个和第三个选项是更多的代码,但是它们会产生更好的结果。

这是一种可以从以下方面入手的方法:

from matplotlib import pyplot as plt

A = [23,45,56,78,32,11]
B = [44,56,78,98]
C = [23,46,67,79]

x = []
y = []
for idx, lst in enumerate((A, B, C)):
    for time in lst:
        x.append(time)
        y.append(idx) 

plt.ylim((-3,5))
plt.yticks([0, 1, 2], ['A', 'B', 'C'])
plt.scatter(x,y, color='r', s=70)
plt.show()

enter image description here

相关问题 更多 >