2013-10-08 63 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

相關問題