如何使用matplotlib在上按时间绘制事件

xmakbtuz  于 2022-11-30  发布在  其他
关注(0)|答案(6)|浏览(175)

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

aabaaabbccacac

2)的

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

vu8f3i0k1#

作为前面答案的扩展,您可以使用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()

或者,您可以尝试以下方法:

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()

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

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()

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

fslejnso

fslejnso2#

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

azpvetkf

azpvetkf3#

您可以从以下方法开始:

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()

rekjcdws

rekjcdws4#

你可能想考虑一下Edward Tufte的The Visual Display of Quantitative Information封面上的火车时刻表显示。这对于显示事件在不同时间的变化率很有用(见第2版第31页的说明),但这只适用于事件发生在不规则时间的情况。
无论哪种方式,其他的答案为你的第二个请求提供了很好的选择。(或axis)plot(x)命令。您可以更改标签,如其他答案中所示,使其成为表示事件的文本。最后,为了模拟列车时刻表图中显示的效果,您可以使用pyplot grid方法(或axes.xaxis.grid)设置网格。

ckx4rj1h

ckx4rj1h5#

在@amillerrhodes的最后一个图的基础上进行构建和简化(同时删除文本部分):

import matplotlib.pyplot as plt
import numpy as np

# run-length encoding, instead of a list of lists with a bunch of zeros
data = [(2, 1), (1, 2), (3, 1), (2, 2), (2, 3), (1, 1), (1, 3), (1, 1), (1, 3)]

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

for i, (num, cat) in enumerate(data):

    if i > 0:
        x_start += data[i-1][0] # get previous end position
    else:
        x_start = i             # start from 0

    x1 = [x_start, x_start+num]

    y1 = [0, 0]
    y2 = [1, 1]

    if cat == 1:
        plt.fill_between(x1, y1, y2=y2, color='red')
    if cat == 2:
        plt.fill_between(x1, y1, y2=y2, color='orange')
    if cat == 3:
        plt.fill_between(x1, y1, y2=y2, color='yellow')

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

enyaitl3

enyaitl36#

基本上,OP需要一个散点图,但是需要一点技巧...

这是我的代码,它可以处理字母类别字符串或单词类别列表。散点图唯一可自定义的方面是标记的大小,您可以添加任意数量的可选参数来控制颜色等。

def crossword(cats, dt, s=900, reverse=False, start=0, all_x=True, ax=None):
    from matplotlib.pyplot import subplot
    ax =ax if ax else subplot()

    # copy input, possibly mutable, length of data, count categories
    data = cats[:]
    l = len(data) ; n = len(set(data))
    # we plot the marker in the centre of its cell
    t = [start+dt/2+dt*i for i in range(l)]
    # data and times are sorted, so that MPL does the "right thing"
    data, t = zip(*sorted(zip(data,t), reverse=reverse))
    # plot the data
    ax.scatter(t, data, marker="s", s=s)
    if all_x:
        ax.set_xticks([start+dt*i for i in range(l+1)])
    else:
        pass
    # trim the axes
    ax.set_xlim((start, start+dt*l))
    ax.set_ylim((-0.5, n-0.5))
    # draw the grid "manually" because on y is off the yticks,
    #                                  on x is denser than the xticks
    for i in range(n): ax.axhline(0.5+i, lw=0.5, color='k')
    for i in range(1,l): ax.axvline(start+dt*i, lw=-.5, color='k')
    # we want the squarish cells to be really square
    ax.set_aspect(dt)
    return ax

from matplotlib.pyplot import subplots, show
fig, ax = subplots(figsize=(10,3.2), layout='constrained')
crossword('aabaaadbbccacac', 0.1, ax=ax, s=1296, reverse=1, all_x=0)
show()

相关问题