matplotlib:共享两个条形图的x轴,每个条形图有4个组

时间:2016-01-28 10:29:17

标签: python matplotlib bar-chart

我正在尝试使用matplotlib创建一个带有两个条形图的图形。每个条形图有4组酒吧。我正在使用的当前python代码如下:

fig,ax=plt.subplots()
bar_width=0.15

rects1 = plt.bar(index, group0, bar_width,
                  alpha=opacity,
                 color='b',
                  label='1')

rects2 = plt.bar(index + bar_width, group1, bar_width,
                  alpha=opacity,
                 color='r',
                  label='2')

rects3 = plt.bar(index + bar_width+bar_width, group2, bar_width,
                  alpha=opacity,
                 color='c',
                  label='3')

rects4 = plt.bar(index + bar_width+bar_width+bar_width, group3, bar_width,
                  alpha=opacity,
                 color='m',
                  label='4')

经过一些格式化后,我获得的情节如下:

enter image description here

现在,我有两个这样的条形图,我希望它们共享x轴。

enter image description here

我无法找到实现这一目标的方法。任何帮助将不胜感激。

由于

1 个答案:

答案 0 :(得分:0)

正如梅尔所建议的,在这种情况下,在同一轴上多次调用bar()。工作代码:

fig,ax=plt.subplots(2,1,sharex=True)
ax1 = plt.subplot(2, 1, 1)
a=ax1.bar(index, rating0,width=0.15,alpha=opacity,
                 color='c'
                  )
index=map(lambda x:x+0.15, index)
b=ax1.bar(index,rating1,width=0.15,alpha=opacity,
                 color='r')
index=map(lambda x:x+0.15, index)
c=ax1.bar(index,rating2,width=0.15,alpha=opacity,
                 color='y')
index=map(lambda x:x+0.15, index)
d=ax1.bar(index,rating3,width=0.15,alpha=opacity,
                 color='m')

index=map(lambda x:x-0.45, index)
ax2 = plt.subplot(2, 1, 2, sharex=ax1)
ax2.bar(index, rating0paris,width=0.15,alpha=opacity,
                 color='c')
index=map(lambda x:x+0.15, index)
ax2.bar(index,rating1paris,width=0.15,alpha=opacity,
                 color='r')
index=map(lambda x:x+0.15, index)
ax2.bar(index,rating2paris,width=0.15,alpha=opacity,
                 color='y')
index=map(lambda x:x+0.15, index)
ax2.bar(index,rating3paris,width=0.15,alpha=opacity,
                 color='m')

for axes in ax:
    format_axes(axes)

同时附上获得的图作为参考: subplots with barcharts