Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib, how to get tick marks inside on one side and outside on the other?

Tags:

matplotlib

I would like to have corresponding tick marks on both the left and right y-axes. However, I would like the left y-axis ticks to be outside the axes and the right y-axis ticks to be inside the axes.

What I have:

import matplotlib.pyplot as plt
ax = plt.subplot(1,1,1)
ax.tick_params(axis='y',which='both',direction='in',right=True)

Is there any way to get the ax.tick_params() to work only on the right axis?

like image 230
NeutronStar Avatar asked Oct 16 '25 05:10

NeutronStar


1 Answers

Ticks are actually the same on both sides of the axes, so one cannot change them for only one side of the axes.

Solution for matplotlib < 3.1:

In addition to @Sheldore's answer, one would probably want to share the twin axes, else both sides come out of sync.

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

ax.tick_params(axis="y", direction='in', length=8)

ax2 = ax.twinx()
ax2.tick_params(direction="out", right=True, length=8)
ax2.get_shared_y_axes().join(ax,ax2)

plt.show()

Solution for matplotlib >= 3.1

Matplotlib 3.1 introduced secondary axes. This is useful in many cases where previously one would have needed to misuse a twin axes, as above. The advantage is that without further arguments, it will be synchronized automatically.

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

ax.tick_params(axis="y", direction='in', length=8)

ax2 = ax.secondary_yaxis("right")
ax2.tick_params(axis="y", direction="out", length=8)

plt.show()

The output is the same in both cases:

enter image description here

like image 54
ImportanceOfBeingErnest Avatar answered Oct 19 '25 15:10

ImportanceOfBeingErnest



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!