基于列表matplotlib中的值绘制矩形

bwitn5fc  于 12个月前  发布在  其他
关注(0)|答案(4)|浏览(89)

假设有一个名单

lst = [0,0,0,1,1,0,1,1]

字符串
我想画:


的数据
代码如下:

fig, ax = plt.subplots() 
 
ax.axvspan(-0.5, 2.5, alpha=0.4, color='yellow')
ax.axvspan(2.5, 4.5, alpha=0.4, color='red')
ax.axvspan(4.5, 5.5, alpha=0.4, color='yellow')
ax.axvspan(5.5, 7.5, alpha=0.4, color='red')


然而,对于更长的列表,需要永远才能实现这一点。有更快的方法吗?

4nkexdtk

4nkexdtk1#

您正在寻找一个条形图,其中条形高度是恒定的,颜色根据lst中的值而变化。

lst = [0,0,0,1,1,0,1,1]

plt.bar(
    x = range(len(lst)),
    height = [1.0 for _ in lst],
    color = ['yellow' if n == 0 else 'red' for n in lst],
    width = 1
)
plt.show()

字符串


的数据

xxb16uws

xxb16uws2#

我自己做的:

def draw_rects(lst):
    res = [list(y) for x, y in groupby(lst)]
    csum = np.cumsum(list(map(len, res))) - 0.5
    vals = [key for key, _group in groupby(lst)]
    
    mapping = {0 : "green", 1 : "purple", 2 : "red", 3 : "yellow"}
    cols = [mapping[x] if x in mapping else x for x in vals]
    fig, ax = plt.subplots() 

    ax.axvspan(-0.5, csum[0], alpha = 0.4, color = cols[0])
    for i in range(len(csum)-1):
        ax.axvspan(csum[i], csum[i+1], alpha = 0.4, color = cols[i+1]) = 0.4, color = cols[i])

字符串

j1dl9f46

j1dl9f463#

您可以通过迭代和依赖连续值来实现这一点。对于较长的列表,它会更快。
举例来说:

import matplotlib.pyplot as plt
lst = [0,0,0,1,1,0,1,1]

plt.bar(
    x = range(len(lst)),
    height = [0.8 for _ in lst],
    color = ['blue' if n == 0 else 'green' for n in lst],
    width = 1
)
plt.show()

字符串


的数据

yxyvkwin

yxyvkwin4#

使用fill_between

lst = np.array([0,0,0,1,1,0,1,1])

x = np.arange(len(lst), dtype= float)
x[ [0, -1]] += [-0.5, 0.5]

plt.fill_between(x, 0, 1-lst, step='mid', color='yellow')
plt.fill_between(x, 0, lst, step='mid', color='red')

字符串
请注意,如果将背景设置为黄色,则只需绘制红色。


的数据

相关问题