2014-01-31 26 views
8

我正在嘗試爲許多國家/地區做一個條形圖,並且我希望名稱顯示在條形圖下方有點旋轉。 問題是標籤之間的空間不規則。Matplotlib Python Barplot:xtick標籤的位置在彼此之間具有不規則空間

Here you can see the barplot with the country names as label

下面是相關代碼:

plt.bar(i, bar_height, align='center', label=country ,color=cm.jet(1.*counter/float(len(play_list)))) 
xticks_pos = scipy.arange(len(country_list)) +1 
plt.xticks(xticks_pos ,country_list, rotation=45) 

有誰知道一個解決方案嗎?

謝謝!您的幫助。

基督教

+0

你可以提供一個完整的工作示例(即數據和導入)供人們玩嗎? –

回答

19

我認爲問題是,XTICK標籤對齊文本的中心,但是當它旋轉你關心它的結束。作爲附註,您可以使用條的位置來選擇更好地處理間隙/不均勻間距的xtick位置。

這是一個使用網絡資源的國家名單(用你自己的,如果你不信任發現我的任意資源谷歌)

import urllib2 
import numpy as np 
import matplotlib.pyplot as plt 

# get a list of countries 
website = "http://vbcity.com/cfs-filesystemfile.ashx/__key/CommunityServer.Components.PostAttachments/00.00.61.18.99/Country-List.txt" 
response = urllib2.urlopen(website) 
page = response.read() 
many_countries = page.split('\r\n') 

# pick out a subset of them 
n = 25 
ind = np.random.randint(0, len(many_countries), 25) 
country_list = [many_countries[i] for i in ind] 

# some random heights for each of the bars. 
heights = np.random.randint(3, 12, len(country_list)) 


plt.figure(1) 
h = plt.bar(xrange(len(country_list)), heights, label=country_list) 
plt.subplots_adjust(bottom=0.3) 

xticks_pos = [0.65*patch.get_width() + patch.get_xy()[0] for patch in h] 

plt.xticks(xticks_pos, country_list, ha='right', rotation=45) 

和結果的柱狀圖,其標籤是一個例子均勻間隔和旋轉: matplotlib bar plot with rotated labels

(你的例子沒有提示顏色是什麼意思,所以這裏省略了,但對於這個問題似乎無關緊要)。

+2

長話短說:將'ha ='right''作爲參數添加到'plt.xticks(...)'。感謝您的解決方案! –