pythonmatplotlibxticksyticks

Different precision on matplotlib axis


My teacher said that in a graph I must label the axis like 0, 0.25, 0.5 not 0.00,0.25,0.50,.... I know how to label it like 0.00,0.25,0.50 (plt.yticks(np.arange(-1.5,1.5,.25))), however, I don't know how to plot the ticklabels with different precision.

I've tried to do it like

plt.yticks(np.arange(-2,2,1))
plt.yticks(np.arange(-2.25,2.25,1))
plt.yticks(np.arange(-1.5,2.5,1))

without avail.


Solution

  • This was already answered, for example here Matplotlib: Specify format of floats for tick lables. But you actually want to have another format than used in the referenced question.

    So this code gives you your wished precision on the y axis

    import matplotlib.pyplot as plt
    import numpy as np
    from matplotlib.ticker import FormatStrFormatter
    
    fig, ax = plt.subplots()
    
    ax.yaxis.set_major_formatter(FormatStrFormatter('%g'))
    ax.yaxis.set_ticks(np.arange(-2, 2, 0.25))
    
    x = np.arange(-1, 1, 0.1)
    plt.plot(x, x**2)
    plt.show()
    

    You can define your wished precision in the String that you pass to FormatStrFormatter. In the above case it is "%g" which stands for the general format. This format removes insignificant trailing zeros. You could also pass other formats, like "%.1f" which would be a precision of one decimal place, whereas "%.3f" would be a precision of three decimal places. Those formats are explained in detail here.