Search code examples
pythonmatplotlibhistogramclip

Python: Histogram - Create uequal bins/axis


Note,this question is related to :[Defining bin width/x-axis scale in Matplotlib histogram. I have a data that looks like this

 Time               Pressure
    1/1/2017 0:00       5.8253
    ...                     ...
    3/1/2017 0:10       4.2785
    4/1/2017 0:20       5.20041
    5/1/2017 0:30       4.40774
    6/1/2017 0:40       4.03228
    7/1/2017 0:50       5.011924
    12/1/2017 1:00      3.9309888

I would like to plot a histogram such that it looks like this.The intervals be like- [0-40,60,65,70,75,80]

enter image description here


Solution

  • You can generate the histogram using numpy.histogram() and then plot it using Axes.bar(). The ticks can then be adjusted using Axes.set_ticklabels(). Here an example:

    import numpy as np
    from matplotlib import pyplot as plt
    
    #some fake data:
    data = np.random.normal(70,20,[100])
    
    #the histogram
    dist, edges = np.histogram(data,bins=[0,40,60,65,70,75,80])
    
    #the plot    
    fig,ax = plt.subplots()    
    ax.bar(
        np.arange(dist.shape[0]), dist, width=1, align = 'edge',
        color = [1,0,0,0.5], edgecolor=[1,0,0,1], lw = 2,
        )
    ax.set_xticks(np.arange(edges.shape[0]))
    ax.set_xticklabels(edges)
    
    plt.show()
    

    The whole thing looks like this:

    result of the above code

    Hope this helps.