Matplotlib Python Barplot:xtick标签的位置彼此之间有不规则的空间

2022-01-25 00:00:00 python matplotlib bar-chart label

问题描述

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

相关文章