Search code examples
matplotlibplotaxisticker

How would I set the y axis to be in millions?


Hi I am wondering how you'd set the y axis of a graph to be millions so instead of it showing 5e7 it would show 50 in the same position. Thank you


Solution

  • You can use tick formatters to show the numbers in millions like shown below

    import numpy as np
    import matplotlib.ticker as ticker
    
    @ticker.FuncFormatter
    def million_formatter(x, pos):
        return "%.1f M" % (x/1E6)
    
    
    x = np.arange(1E7,5E7,0.5E7)
    y = x
    fig, ax = plt.subplots()
    
    ax.plot(x,y)
    
    ax.xaxis.set_major_formatter(million_formatter)
    ax.yaxis.set_major_formatter(million_formatter)
    
    ax.set_xlabel('X in millions')
    ax.set_ylabel('Y in millions')
    
    plt.xticks(rotation='45')
    
    plt.show
    

    which results in

    enter image description here