如何并排绘制具有不同X坐标的条形图

时间:2014-09-16 19:36:16

标签: python python-2.7 matplotlib

我看过许多关于使用条形图并排绘图的帖子。我有一些数组,X坐标不一定相同。如果我尝试使用wbins1和/或bins2添加和减去bins3,我会收到错误消息。我还尝试使用arrange(bins1)中的numpy并收到错误。

import matplotlib.pyplot as plt

#first data set
bins1= [1,2,3,4,5,6,7]
frequency1= [2,27,70,91,45,11,7]

#second data set
bins2= [5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
frequency2= [2,4,6,7,6,13,4,3,13,4,5,7,6,1,1,1]

#third data set
bins3= [2,3,4,5,6,7,8,9,10,11,12,14]
frequency3= [1,8,21,27,33,14,17,23,4,2,1,1]

#width
w= 0.3

#plot
plt.figure()

#modify to print side by side
plt.bar(bins1, frequency1, width=w, color='r', align='center', label='QD128')
plt.bar(bins3, frequency3, width=w, color='g', align='center', label='QD16')
plt.bar(bins2, frequency2, width=w, color='b', align='center', label='QD1')

plt.show()

这是当前代码的图像: This is what the current code outputs like

这更像是我想要的,但它来自直方图,而不是条形图:

enter image description here

1 个答案:

答案 0 :(得分:1)

我能够使用直方图而不是条形图得到我想要的东西:

import matplotlib.pyplot as plt

bins1= [1,2,3,4,5,6,7]
frequency1= [2,27,70,91,45,11,7]
bins2= [5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
frequency2= [2,4,6,7,6,13,4,3,13,4,5,7,6,1,1,1]
bins3= [2,3,4,5,6,7,8,9,10,11,12,14]
frequency3= [1,8,21,27,33,14,17,23,4,2,1,1]


plt.figure()

plt.hist([bins1, bins2, bins3], 20, weights=[frequency1, frequency2, frequency3], 
            histtype='bar', label=['QD128','QD1','QD16'])

plt.legend()

plt.show()

结果如下:

enter image description here

相关问题