Search code examples
pythonpython-3.xmatplotlibhistogrambinning

For a histogram, how can I keep all specified bin-ticks along the x-axis and show number-labels only for specified bin-ticks?


I have a histogram with centered bin-ticks.

As seen in the picture, the numbered labels of each bin-tick are so close to each other that the numbers are not as legible as I'd like them to be. I would like to keep the centered bin-ticks in my plot, but with labeling the value of every other bin-tick.

As an example, the first bin-tick is 2.5 and each bin-width is 5, so the next bin-tick is 7.5, the one after that is 12.5, etc. I would like the tick-marks on the x-axis to be visible at 2.5, 7.5, 12.5, etc, but I would like only the number-label 2.5, 12.5, etc to be visible on the x-axis.

How could I go about doing this? The code to create a histogram similar to mine (dependent on random module for values) is posted below.

PS - I could decrease the number of bins to fit all the numbered-labels along the x-axis, but I would prefer to keep the number of bins as is because I am applying this base case to a much larger dataset with specified bin numbers.

import random
a = 48
b = 8
randg = []
for index in range(100):
    randg.append( random.gauss(a,b) )
data = sorted(randg)

small = 0 
big = 100 
numbins = 20 
binwide = (big - small) / numbins 
binleft = [] # left boundaries of bins
for index in range(numbins):
    binleft.append(small + index * binwide)
binbounds = [val for val in binleft] 
binbounds.append(big) # don't forget right boundary of last bin

binmids = [] # midpt of bins (for ticks)
for index in range(len(binbounds)-1):
    binmids.append( binwide/2 + index * binwide )

import matplotlib.pyplot as plt
plt.hist(data, bins = binbounds)
plt.xticks(binmids)
plt.show()

Solution

  • If you are fine with omitting every second tick as well, an easy solution is to set the ticks to only every second entry of the binmids list.

    plt.xticks(binmids[::2]) 
    

    enter image description here

    If this is not an option, you can set the ticks to the complete binmids list, but then set every other ticklabel to an empty string ("").

    plt.xticks(binmids)
    ticklabels = [ binmids[i] if i % 2 == 0 else "" for i in range(len(binmids)) ]
    plt.gca().set_xticklabels( ticklabels )
    

    enter image description here