Matplotlib Python Barplot:xtick标签的位置彼此之间有不规则的空间 [英] Matplotlib Python Barplot: Position of xtick labels have irregular spaces between eachother

查看:29
本文介绍了Matplotlib Python Barplot:xtick标签的位置彼此之间有不规则的空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I'm trying to do a bar plot for many countries and i want the names displayed a bit rotated underneath the bars. The problem is that the spaces between the labels are irregular.

Here's the relevant code:

 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 )

Does anyone know a solution?

Thanks! For your Help.

Christian

解决方案

I think the problem is that the xtick label is aligned to the centre of the text, but when it is rotated you care about the end of it. As a side note, you can use the position of the bars to select the xtick positions which better handles gaps/uneven spacing.

Here's an example that uses a web resource for list of countries (use your own if you don't trust the arbitrary resource google found for me)

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('
')

# 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)

and results in a bar chart whose labels are evenly spaced and rotated:

(your example doesn't give a hint as to what the colours mean so that's omitted here, but seems immaterial to the question anyway).

这篇关于Matplotlib Python Barplot:xtick标签的位置彼此之间有不规则的空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆