Change grid interval and specify tick labels

There are several problems in your code.

First the big ones:

  1. You are creating a new figure and a new axes in every iteration of your loop →
    put fig = plt.figure and ax = fig.add_subplot(1,1,1) outside of the loop.

  2. Don’t use the Locators. Call the functions ax.set_xticks() and ax.grid() with the correct keywords.

  3. With plt.axes() you are creating a new axes again. Use ax.set_aspect('equal').

The minor things:
You should not mix the MATLAB-like syntax like plt.axis() with the objective syntax.
Use ax.set_xlim(a,b) and ax.set_ylim(a,b)

This should be a working minimal example:

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

# Major ticks every 20, minor ticks every 5
major_ticks = np.arange(0, 101, 20)
minor_ticks = np.arange(0, 101, 5)

ax.set_xticks(major_ticks)
ax.set_xticks(minor_ticks, minor=True)
ax.set_yticks(major_ticks)
ax.set_yticks(minor_ticks, minor=True)

# And a corresponding grid
ax.grid(which="both")

# Or if you want different settings for the grids:
ax.grid(which="minor", alpha=0.2)
ax.grid(which="major", alpha=0.5)

plt.show()

Output is this:

result

Leave a Comment