Beaker
Beaker

Reputation: 199

Matplotlib won't show minor ticks when using subplots

I have several subplots and want to adjust the axis ticks settings by ax.tick_params. Everything works fine, however, the minor ticks are not shown. Here is a code example

import matplotlib.pyplot as plt

x = np.linspace(0,1,100)
y = x*x

f, (ax1,ax2) = plt.subplots(2, 1)

ax1.tick_params(axis="both", direction="in", which="both", right=False, top=True)
ax2.tick_params(axis="both", direction="in", which="both", right=True, top=False)

ax1.plot(x,y)
ax2.plot(x,-y)

plt.show()

I assumed that which=both would give me the minor ticks. However I need to add an additional

plt.minorticks_on()

which makes them visible but only in ax2.

How do I fix this?

Upvotes: 7

Views: 9758

Answers (2)

Sheldore
Sheldore

Reputation: 39042

plt would work on the current axis which is ax2 in your case. One way is to first enable them using the way you did and then specify the number of minor ticks using AutoMinorLocator

from matplotlib.ticker import AutoMinorLocator

ax1.tick_params(axis="both", direction="in", which="both", right=False, top=True)
ax2.tick_params(axis="both", direction="in", which="both", right=True, top=False)

ax1.plot(x,y)
ax2.plot(x,-y)

for ax in [ax1, ax2]:
    ax.xaxis.set_minor_locator(AutoMinorLocator(4))
    ax.yaxis.set_minor_locator(AutoMinorLocator(4))

enter image description here

Upvotes: 3

M-Wane
M-Wane

Reputation: 173

With pyplot the danger is that you loose track of which one the current axes is that a command like plt.minorticks_on() operates on. Hence it would be beneficial to use the respective methods of the axes you're working with:

ax1.minorticks_on()
ax2.minorticks_on()

Upvotes: 6

Related Questions