Home > other >  Change y-axis ticks only on RHS
Change y-axis ticks only on RHS

Time:04-15

I'm looking to change the values at which there are ticks, for the right hand side y-axis (but NOT the left).

Here's a MWE:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()


ax.plot([1, 2, 3], [1, 2, 3])

ax.tick_params(axis="y", which="both", labelright="on")
ax.tick_params(axis="y", which="both", labelleft="on", labelright="on")

ax.set_yticks([1, 2, 3])

plt.show()

With the set_yticks command I get the behavior on both axes:

enter image description here

For reference, here are the default ticks:

enter image description here

I'm looking for something like

ax.set_yticks([1, 2, 3], which='right')

so that I can have ticks every 0.25 on the left axis, and ticks every 1 on the right axis. Any ideas?

CodePudding user response:

One possible solution is to "twin" the axis:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(1, 3)
y = np.linspace(1, 3)

fig, ax1 = plt.subplots()
ax1.plot(x, y)

ax2 = ax1.twinx()  # instantiate a second axes that shares the same x-axis
# set the new ylimits to the be the same as the other
ax2.set_ylim(ax1.get_ylim())
ax2.set_yticks([1, 2, 3])

fig.tight_layout()  # otherwise the right y-label is slightly clipped
plt.show()

enter image description here

  • Related