【问题标题】:bar chart dynamic reference line length条形图动态参考线长
【发布时间】:2015-11-27 16:37:08
【问题描述】:

我在条形图中有一条参考线,但我希望该线根据 x 轴的索引长度动态调整。我希望这条线从最左边栏的左边缘开始,到最右边栏的右边缘结束。我注意到当 ind (index) 的值发生变化时,我无法通过使用 ind 的百分比或 xmin 和 xmax 参数的常数来准确地进行调整。

这是一个从 matplotlib 站点稍作修改的示例: http://matplotlib.org/examples/pylab_examples/bar_stacked.html

import numpy as np
import matplotlib.pyplot as plt


N = 5
menMeans = (20, 35, 30, 35, 27)
womenMeans = (25, 32, 34, 20, 25)
menStd = (2, 3, 4, 1, 2)
womenStd = (3, 5, 2, 3, 3)
ind = np.arange(N)    # the x locations for the groups
width = 0.35       # the width of the bars: can also be len(x) sequence

p1 = plt.bar(ind, menMeans, width, color='r', yerr=menStd)
p2 = plt.bar(ind, womenMeans, width, color='y',
             bottom=menMeans, yerr=womenStd)

#How do I adjust the length of this line dynamically?
plt.axhline(linewidth=1, color='b', y=np.average(menMeans))
plt.ylabel('Scores')
plt.title('Scores by group and gender')
plt.xticks(ind + width/2., ('G1', 'G2', 'G3', 'G4', 'G5'))
plt.yticks(np.arange(0, 81, 10))
plt.legend((p1[0], p2[0]), ('Men', 'Women'))

plt.show()

提前致谢!

【问题讨论】:

  • 我添加了一个答案,但我不确定这就是你的意思。如果您还需要其他东西,请告诉我。
  • 谢谢,安德拉斯。我试过这个(在 *2 之前没有额外的括号)但我得到了错误:x 和 y 必须具有相同的第一个维度。
  • 我意识到我需要复制 y,正如你所说,一切顺利。
  • 因此,如果这确实是您需要的,请考虑将我的答案标记为已接受:)

标签: python matplotlib plot


【解决方案1】:

您可以使用bar 图的明确定义的width 参数手动绘制一条适合您需要的线:

p1 = plt.bar(ind, menMeans, width, color='r', yerr=menStd)
p2 = plt.bar(ind, womenMeans, width, color='y',
         bottom=menMeans, yerr=womenStd)

#line with adjusted length
plt.plot([min(ind), max(ind)+width], np.average(menMeans)]*2,linewidth=1,color='b')

我们只需定义一对xy 坐标来生成线作为plotx[min(ind), max(ind)+width] 给出,y 是具有值np.average(menMeans) 的重复向量。正确的x 值可以从您的示例代码将xticks 放置在ind+width/2 的事实中推断出来,并且我们知道条形的宽度正好是width

结果:

【讨论】:

    猜你喜欢
    • 2018-06-07
    • 1970-01-01
    • 2016-08-08
    • 2019-01-01
    • 1970-01-01
    • 2019-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多