在Python(matplotlib)中将水平线插入直方图。

19 浏览
0 Comments

在Python(matplotlib)中将水平线插入直方图。

如何在这个直方图中添加一条水平线?我已经尝试了通常的方法(对于条形图来说有效),但是由于y轴是以百分比为单位的(我猜测),所以无法绘制出线条。我试图绘制一条存在于从小时(x坐标)11到小时(x坐标)22的线条,以展示实验条件的变化。有人知道该怎么做吗?谢谢!

probability_list = np.array(probability_list, dtype=float)
x = 24
f, ax = plt.subplots(1, 1, figsize=(10, 5))
heights, bins = np.histogram(probability_list, bins=len(list(set(probability_list))))
percent = [i / len(dayammount) * 100 for i in heights]
ax.bar(bins[:-1], percent, width=.025, align="edge")
vals = ax.get_yticks()
ax.set_yticklabels(['%1.2f%%' % i for i in vals])
plt.xlim(xmin=0, xmax=24)
plt.xticks(range(0, 25))
plt.xlabel('Time (Hours)')
plt.ylabel('Probability of Sound (%)')
plt.show()

0
0 Comments

问题出现的原因是因为y轴是以百分比为单位。解决方法有两种:

1. 使用hlines方法,在xmin=11xmax=22之间绘制一个边界的水平线,例如在y=2处:

ax.hlines(y=2, xmin=11, xmax=22, colors='k', linestyles='--')

2. 或者使用普通的plot方法:

ax.plot([11, 22], [2, 2], 'k--')

这是一些模拟数据的输出结果:

![histogram with hlines](https://i.stack.imgur.com/t6qgY.png)

非常感谢,发现是xmin/xmax有错误。

0