Python Matplotlib布尔打印矩形填充
我想用Matplotlib和Python创建一个布尔数据图。我有几个布尔通道,如果通道=1(或真),我想用颜色填充 我找到了 这显示了我想要的基本情况 . 我目前的想法是使用多个子图共享x轴,并使用Python Matplotlib布尔打印矩形填充,python,matplotlib,Python,Matplotlib,我想用Matplotlib和Python创建一个布尔数据图。我有几个布尔通道,如果通道=1(或真),我想用颜色填充 我找到了 这显示了我想要的基本情况 . 我目前的想法是使用多个子图共享x轴,并使用fill\u-between来填充通道=1的时间 在我继续编写代码之前,我想知道Matplotlib中是否已经有一些东西可以让这变得更容易?我不想担心y值来控制高度,而是更像是一个水平条形图,只是我的x轴是时间序列,条形图中有间隙。我用matplotlib解决了这个问题 我还使用了一个函数来查找数
fill\u-between
来填充通道=1的时间
在我继续编写代码之前,我想知道Matplotlib中是否已经有一些东西可以让这变得更容易?我不想担心y值来控制高度,而是更像是一个水平条形图,只是我的x轴是时间序列,条形图中有间隙。我用matplotlib解决了这个问题
我还使用了一个函数来查找数组中真值的起始idx和结束idx。我是从SO的另一个帖子上得到的,但我现在找不到
import numpy as np
def findones(a):
isone = np.concatenate(([0], a, [0]))
absdiff = np.abs(np.diff(isone))
ranges = np.where(absdiff == 1)[0].reshape(-1, 2)
return np.clip(ranges, 0, len(a) - 1)
def plotbooleans(ax, dictofbool):
ax.set_ylim([-1, len(dictofbool)])
ax.set_yticks(np.arange(len(dictofbool.keys())))
ax.set_yticklabels(dictofbool.keys())
for i, (key, value) in enumerate(dictofbool.items()):
indexes = findones(value)
for idx in indexes:
if idx[0] == idx[1]:
idx[1] = idx[1]+1
ax.hlines(y=i, xmin=idx[0], xmax=idx[1], linewidth=10, colors='r')
return ax
测试代码:
import matplotlib.pyplot as plt
testarray = np.array([1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1])
testbool = {}
for i in range(0, 5):
testbool['bool_{}'.format(i)] = testarray
fig, ax = plt.subplots()
ax = plotbooleans(ax, testbool)
plt.grid()
plt.subplots_adjust(bottom=0.2)
plt.show()
输出应如下所示:
matplotlib图库总是值得一探究竟。单击任何图像以查看生成该图像的代码。特别是,这看起来很相关:这将类似于,因为fill-between将where作为布尔参数。仍然有用的是有另一种方法来尝试它。