【问题标题】:Inserting a Horizontal Line into Histogram in Python (matplotlib)? [duplicate]在 Python(matplotlib)中将水平线插入直方图中? [复制]
【发布时间】:2021-10-11 17:27:34
【问题描述】:

如何在直方图中添加一条水平线?我已经尝试过通常的方法(适用于条形图),但是由于 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()

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    但是由于 y 轴以百分比表示(我假设),因此该线没有绘制

    一般而言,将heights 转换为percents 并不重要——无论哪种方式,matplotlib 都会看到一个值列表。

    目前尚不清楚您尝试了什么,但这里有几个选项:

    • 使用hlines 绘制有界水平线,例如在y=2xmin=11xmax=22

      ax.hlines(y=2, xmin=11, xmax=22, colors='k', linestyles='--')
      
    • 或者使用普通的plot:

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

    我没有你的原始数据,但这是一些模拟数据的输出:

    【讨论】:

    • 非常感谢,发现是 xmin/xmax 的错误。
    猜你喜欢
    • 2013-04-17
    • 2013-05-31
    • 1970-01-01
    • 1970-01-01
    • 2018-02-26
    • 1970-01-01
    • 1970-01-01
    • 2021-03-03
    相关资源
    最近更新 更多