Search code examples
pythonmatplotlibplotlabelaxes

Matplotlib axis custom scale adjustment


I am plotting from a pandas dataframe with commands like

fig1 = plt.hist(dataset_1[dataset_1>-1.0],bins=bins,alpha=0.75,label=label1,normed=True) 

and the plots comprise multiple histograms on one canvas. Since each histogram is normalised to its own integral (hence the histograms have the same area, because the purpose of the histograms is to illustrate the shape of the datasets rather than their relative sizes), the numbers on the y axis are not meaningful. For now, I am suppressing y axis labelling using

axes.set_ylabel("(Normalised to unity)")

axes.get_yaxis().set_ticks([])

Is there a way of adjusting the scaling of the y axis such that "1" corresponds to the highest value on any histogram? This would display a vertical scale to guide the eye and with which to judge the relative values of different bins. In essence, I mean re-normalising the maximum displayed y value without affecting the scaling of the histograms (i.e. decoupling the axis scale from what it represents).


Solution

  • You have two options:

    Drawing histogram, adjusting y axis tick.

    You may set the y tick to the location of the maximum and label it with 1 afterwards.

    import numpy as np; np.random.seed(1)
    import matplotlib.pyplot as plt
    
    a = np.random.rayleigh(scale=3, size=2000)
    
    hist, edges,_ = plt.hist(a, ec="k")
    plt.yticks([0,hist.max()], [0,1])
    
    plt.show()
    

    Normalizing histogram, drawing to scale.

    You may normalize the histogram in the way you desire by first calculating the histogram, dividing it by its maximum and then plot a bar plot of it.

    import numpy as np; np.random.seed(1)
    import matplotlib.pyplot as plt
    
    a = np.random.rayleigh(scale=3, size=2000)
    
    hist, edges = np.histogram(a)
    hist = hist/float(hist.max())
    
    plt.bar(edges[1:], hist, width=np.diff(edges)[0], align="edge", ec="k")
    plt.yticks([0,1])
    
    plt.show()
    

    The output in both cases would be the same:

    enter image description here