Search code examples
pythonmatplotlibhistogram

How can I change the x axis in matplotlib histogram?


import matplotlib.pyplot as plt
import numpy as np

x = np.arange(1,30)
plt.hist(x,bins=10, edgecolor='k')
plt.title('Histogram')


plt.show()

I have ten bins, and I wish to make x axisclooks like: (['first','second','third','fourth','fifth','sixth','seventh','eighth','ninth','tenth']) I did use this, but gives an error: plt.xticks(['first','second','third','fourth','fifth','sixth','seventh','eighth','ninth','tenth'])


Solution

  • plt.hist() returns 3 lists:

    • the counts (values) inside each bin
    • the edges of the bins (e.g. 11 edges when there are 10 bins)
    • the graphical elements with the rectangular bars

    Averaging out the bin edges, will give the positions of the centers of the bars. These can be used to nicely locate the tick labels.

    import matplotlib.pyplot as plt
    import numpy as np
    
    x = np.random.uniform(1, 30, 100)
    _values, bin_edges, _rectangles = plt.hist(x, bins=10, edgecolor='k', facecolor='turquoise')
    plt.xticks((bin_edges[:-1] + bin_edges[1:]) / 2,
               ['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', 'tenth'])
    plt.title('Histogram')
    plt.margins(x=0.02)
    plt.tight_layout()
    plt.show()
    

    histogram with custom x tick labels