Matplotlib Python Barplot: Position of xtick labels have irregular spaces between eachother

匿名 (未验证) 提交于 2019-12-03 01:12:01

问题:

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

回答1:

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

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



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!