Pyplot Barchart:条不能正确地围绕xticks分组

时间:2019-03-12 10:34:33

标签: python-2.7 matplotlib

我正在尝试在条形图中围绕xticks分组四个条形。这里有一些示例数据(请注意,我在Python 2.7中运行此示例)和我的代码。

import matplotlib.pyplot as plt
import numpy as np

xps_s1 = range(2008, 2019)
xps_s2 = range(2012, 2019)
xps_s3 = range(2013, 2019)
xps_s4 = range(2014, 2019)
yps_s1 = [94.6, 93.9, 93, 94.7, 94.6, 95.4, 95, 93.6, 93, 93.6, 92.2]
yps_s2 = [81.5, 90.2, 91.5, 94, 95, 94.3, 95.3]
yps_s3 = [83.9, 92.7, 93.3, 94.4, 94.4, 94.6]
yps_s4 = [90.6, 95, 94.8, 94, 93.9]

y_means = [94.6, 93.9, 93, 94.7, np.mean([81.5, 94.6]), 
           np.mean([83.9, 90.2, 95.4]), np.mean([92.7, 91.5, 95, 90.6]), 
           np.mean([93.3, 94, 93.6, 95]), np.mean([94.4, 95, 93, 94.8]), 
           np.mean([94.4, 94.3, 93.6, 94]), np.mean([91.4, 94.6, 95.3, 92.2, 93.9])]

fig = plt.subplots()
ax = plt.axes(xlim=(2007,2019), ylim=(75, 100))

w = 0.2
plt.xticks(np.arange(2008, 2019, step = 1))

rects1 = ax.bar([x-w for x in xps_s1], yps_s1, width=w, align="center",
                color='goldenrod', label='Sample1')

rects2 = ax.bar([x-w*2 for x in xps_s2], yps_s2, width=w, align="center",
                color='grey', label='Sample2')

rects3 = ax.bar([x+w for x in xps_s3], yps_s3, width=w, align="center",
                color='silver', label='Sample3')

rects4 = ax.bar([x+w*2 for x in xps_s4], yps_s4, width=w, align="center",
                color='thistle', label='Sample4')

mean_line =ax.plot(xps_s1,y_means, label='Overall', 
                       linestyle='-', color = "indianred")

legend = ax.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)

plt.show()

当我有三个横条时,我设置了w = 0.3,并且横条很好地围绕了刻度线(我将rects1紧紧地坐在刻度线上,另外两个紧靠其侧翼,其余的.09设置了宽度相隔多年

现在,使用上面的代码,它们似乎实际上与任何刻度都不相关,并且它们不能正确分组。

我在做什么错了?

非常感谢!

0 个答案:

没有答案