durbachit
durbachit

Reputation: 4886

matplotlib locator_params or set_major_locator not working

I am trying to reduce the number of axis ticks in subplots (each axis different values, so I can't set the ticks manually), but other answers such as this or this don't work. My syntax for creating the figure is standard, as follows:

fig = plt.figure(figsize=(7,9))
ax = fig.add_subplot(8,2,i+1) # I am plotting in a much larger loop, but I don't think there is anything wrong with the loop, because everything else (axis limits, labels, plotting itself...) works fine.

and to reduce the number of yticks, I tried

ax = plt.locator_params(nbins=4, axis='y')

which raised the error TypeError: set_params() got an unexpected keyword argument 'nbins'

and I tried

ax.yaxis.set_major_locator(plt.MaxNLocator(4))

which gave the error AttributeError: 'NoneType' object has no attribute 'yaxis'

I don't understand why my subplot is considered to be a NoneType. I suspect this is the core of the problem, but all examples that I saw have the same structure, i.e.

fig = plt.figure()
ax = fig.add_subplot(111)
ax.yaxis.set_major_locator(plt.MaxNLocator(4))

and it should work. So why is my ax NoneType?

Upvotes: 6

Views: 13066

Answers (1)

tmdavison
tmdavison

Reputation: 69116

The problem is the line:

ax = plt.locator_params(nbins=4, axis='y')

locator_params does not return an Axes instance (in fact it doesn't return anything), so on this line you are reassigning ax to be None.

I think you want to change it to:

ax.locator_params(nbins=4, axis='y')

and then it should all work ok.

Upvotes: 3

Related Questions