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

后端 未结 1 1682
心在旅途
心在旅途 2020-12-09 13:27

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 irre

相关标签:
1条回答
  • 2020-12-09 13:48

    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: matplotlib bar plot with rotated labels

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

    0 讨论(0)
提交回复
热议问题