Search code examples
pythonmatplotlibaxis-labels

Restore matplotlib default axis ticks


My question is that how can I restore matplotlib default axis ticks after changing them. For example, in the code below, I plotted squares of numbers for 1 to 9 and then changed yticks to [20, 40, 60]. Default yticks for this plot was [0, 10, 20, 30, 40, 50, 60, 70, 80] before I changed them. So, from now on, how can I bring back those default yticks?

import matplotlib.pyplot as plt
import numpy as np
x = np.arange(9) + 1
y = x ** 2
fig, ax1 = plt.subplots()
ax1.plot(x, y)
ax1.set_yticks([20, 40, 60])
plt.show()

Solution

  • I have found an answer to my own question. As stated in matplotlib documentation, AutoLocator is the default tick locator for most plotting. To enable AutoLocator, look at the re-edited version of my script below.

    import matplotlib.pyplot as plt
    import numpy as np
    from matplotlib.ticker import AutoLocator
    
    x = np.arange(9) + 1
    y = x ** 2
    
    fig, ax1 = plt.subplots()
    ax1.plot(x, y)
    ax1.set_yticks([20, 40, 60])
    ax1.yaxis.set_major_locator(AutoLocator())  # solution
    
    plt.show()