Search code examples
pythonmatplotlibgridxticks

Matplotlib custom ticks and grids in groups


I am trying to insert custom ticks to a plot in batches with defined distances. I can do this by manually adding them, but I am looking for a better way.

Example:

import matplotlib.pyplot as plt

x = [-5, 5]
y = [1, 5]
plt.plot(x, y)

plt.xlim(-10, 10)
plt.grid(axis="x", which='major', color='r', linestyle='--')

plt.yticks([])

# Adding custom ticks 
cticks = [-8, -7, -6, -5, 1, 2, 3, 4]
plt.xticks(cticks)

plt.show()

Resulting Plot

Here's what I have tried:

import matplotlib.pyplot as plt
import numpy as np

x = [-5, 5]
y = [1, 5]
plt.plot(x, y)

plt.xlim(-10, 10)
plt.grid(axis="x", which='major', color='r', linestyle='--')
plt.xticks(np.arange(1 , 5, step=1))

plt.yticks([])

plt.show()

Resulting Plot

But this gives only one batch.

Question: Is there a similar way to include more batches of tick marks and grids on the x-axis at desired positions?


Solution

  • IIUC you don't want to specify all ticks manually but only the batches. You can to this in a loop that will extend cticks:

    import matplotlib.pyplot as plt
    
    x = [-5, 5]
    y = [1, 5]
    plt.plot(x, y)
    
    plt.xlim(-10, 10)
    plt.grid(axis="x", which='major', color='r', linestyle='--')
    
    plt.yticks([])
    
    # Adding custom ticks
    cticks = []
    for n in [-8, 1]: # specify the beginning of each batch here
        cticks += range(n, n+4)
    plt.xticks(cticks)
    
    plt.show()
    

    Output:

    enter image description here