Matplotlib Python Barplot: xtick shortcut position has wrong spacing between each other

I am trying to make the bar for many countries, and I want the names to appear a little under the bars. The problem is that spaces between labels are irregular.

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

Here is 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 reference.

Christian

+8
python matplotlib label bar-chart
source share
1 answer

I think the problem is that the xtick label is centered on the text, but when it is rotated, you take care of its end. As an extra note, you can use the position of the bars to select the xtick positions that better handle gaps / uneven distance.

Here is an example that uses a web resource for a list of countries (use your own if you do not trust the arbitrary google resource 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 leads to the creation of a histogram whose labels are evenly distributed and rotated: matplotlib bar plot with rotated labels

(your example does not give a hint of what the colors mean to omit here, but in any case seems inconsequential to the question).

+19
source share

All Articles