条形图动态参考线长度

2024-06-08 04:42:31 发布

您现在位置:Python中文网/ 问答频道 /正文

在条形图中有一条参考线,但我希望该线根据x轴的索引长度进行动态调整。我希望这条线从最左边的酒吧的左边开始,到最右边的酒吧的右边结束。当我注意到,用xmind的百分数调整时,我不能精确地调整xmind的值。在

下面是一个从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()

提前谢谢!在


Tags: theimportmatplotlibasnpbarpltwidth
1条回答
网友
1楼 · 发布于 2024-06-08 04:42:31

您可以使用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坐标来生成plot的直线。x[min(ind), max(ind)+width]给出,y是一个值为np.average(menMeans)的重复向量。正确的x值可以从示例代码将xtick放在ind+width/2的事实中推断出来,我们知道这些条的宽度正好是width。在

结果:

bar plot with adjusted horizontal line

相关问题 更多 >

    热门问题