Search code examples
python-2.7matplotlibaxis-labels

Set Python to custom-set y-axis minor tick mark frequency


This question is related to plotting minor tick mars on the y-axis in a Python plot with matplotlib.

Here is the code that I have:

import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator

fig, ax = plt.subplots()
fig.set_facecolor('white')

x = [1,2,3]
plt.subplot(211)
plt.plot([1,2,3], label="test1")
plt.plot([3,2,1], label="test2")
plt.xticks()
plt.yticks()
ax.yaxis.set_minor_locator(MultipleLocator(5))
plt.show()

When I generate this plot, I am not getting any minor tick marks.

I have attached here the plot that this code gives me. enter image description here

Is it possible for me to display the minor tick marks for the y-axis here?


Solution

  • You can set what ticks you want in plt.yticks() , the input can be a numpy array which you generate beforehand

    import matplotlib.pyplot as plt
    from matplotlib.ticker import MultipleLocator
    import numpy as np
    
    fig, ax = plt.subplots()
    fig.set_facecolor('white')
    
    yticks = np.arange(1,3,0.2)
    
    x = [1,2,3]
    plt.subplot(211)
    plt.plot([1,2,3], label="test1")
    plt.plot([3,2,1], label="test2")
    plt.xticks()
    plt.yticks(yticks)
    ax.yaxis.set_minor_locator(MultipleLocator(5))
    plt.show()
    

    which gives you :

    enter image description here