【发布时间】: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