2013-10-08 66 views
2

我正在使用matplotlib在级联图表(东西在this style)。我想让所有不同宽度的酒吧彼此齐平,但我希望底部的酒吧从1到7有规律地增加,而与酒吧无关。然而,此刻,它看起来像这样:如何在matplotlib中独立于刻度设置条宽?

Barchart with irregularly spaced bars

到目前为止,这是我的本钱:

python 

import numpy as np 
import matplotlib.pyplot as plt 
from matplotlib.ticker import MultipleLocator, FormatStrFormatter 


n_groups = 6 
name=['North America','Russia','Central & South America','China','Africa','India'] 

joules = [33.3, 21.8, 4.22, 9.04, 1.86, 2.14] 
popn=[346,143,396,1347,1072,1241] 

fig, ax = plt.subplots() 

index = np.arange(n_groups) 
bar_width = [0.346,.143,.396,1.34,1.07,1.24] 

opacity = 0.4 

rects1 = plt.bar(index+bar_width, joules, bar_width, 
       alpha=opacity, 
       color='b', 
       label='Countries') 

def autolabel(rects): 
    # attach some text labels 
    for ii,rect in enumerate(rects): 
     height = rect.get_height() 
     ax.text(rect.get_x()+rect.get_width()/2., 1.05*height, '%s'%(name[ii]), 
       ha='center', va='bottom') 

plt.xlabel('Population (millions)') 
plt.ylabel('Joules/Capita (ten billions)') 
plt.title('TPEC, World, 2012') 
plt.xticks(1, ('1', '2', '3', '4', '5','6') 
autolabel(rects1) 

plt.tight_layout() 
plt.show() 

和所有的变化我到目前为止已经试过调整酒吧间距导致了类似的问题。有任何想法吗?

+0

摆脱蜱虫,只需使用'文本'或'注释'来添加标签。 – tacaswell

回答

2

目前的问题是您的index是一个常规序列,因此每个小节的左侧边缘定期定位。你想要的是将index作为一个条形x值的总计,以便每个条形的左边与上一条的右边对齐。

可以使用np.cumsum()做到这一点:

... 
index = np.cumsum(bar_width) 
... 

现在index将在bar_width[0]开始,所以你需要这些小节的左手边缘设置为index - bar_width

rects1 = plt.bar(index-bar_width, ...) 

结果:

enter image description here

你当然想玩弄轴线限制和标签位置,使它看起来不错。

+0

D'oh,谢谢!完美的修复。 – RSid

+0

你也可以使用'align ='center'' – tacaswell

相关问题