gpt4 book ai didi

python - Matplotlib bool 图矩形填充

转载 作者:行者123 更新时间:2023-12-05 04:06:41 25 4
gpt4 key购买 nike

我想用 Matplotlib 和 Python 创建一个 bool 数据图。我有几个 bool channel ,如果 channel = 1(或 True),我想填充一种颜色

我找到了 this C# question这几乎显示了我想要的底部情节 this image .

我目前的想法是使用具有共享 x 轴的多个子图,并使用 fill_between 来填充我的 channel =1 的时间。

在我继续编写代码之前,我想知道 Matplotlib 中是否已经有一些东西可以使这更容易?我不想担心 y 值来控制高度,而是将它更像是一个水平条形图,除了我的 x 轴是时间序列并且我的条中有间隙。

最佳答案

我用过 matplotlib ax.hlines解决这个问题。

我还使用了一个函数来查找数组中真值的开始和结束 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()

输出应该是这样的: boolean plot

关于python - Matplotlib bool 图矩形填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49634844/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com