条形图动态参考线长度

时间:2015-11-27 16:37:09

标签: python matplotlib plot

我在条形图中有一条参考线,但我希望该线根据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()

提前致谢!

1 个答案:

答案 0 :(得分:2)

您可以使用width图表中明确定义的bar参数手动绘制符合您需求的行:

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坐标即可生成plot行。 x[min(ind), max(ind)+width]提供,y是值为np.average(menMeans)的重复向量。从您的示例代码将x放置在xtick这一事实可以推断出正确的ind+width/2值,并且我们知道条形码&#39}。宽度恰好是width

结果:

bar plot with adjusted horizontal line