I have a simple line plot and need to move the y-axis ticks from the (default) left side of the plot to the right side. Any thoughts on how to do this?
5 Answers
Use ax.yaxis.tick_right()
for example:
from matplotlib import pyplot as plt
f = plt.figure()
ax = f.add_subplot(111)
ax.yaxis.tick_right()
plt.plot([2,3,4,5])
plt.show()
-
1Great answer, you get a +1, I'd give you another +1 for the picture but I'm limited to only 1. Commented Apr 27, 2012 at 17:23
-
interesting that this causes the tick names to come back even though they should be suppressed by sharey=True– endolithCommented Dec 17, 2017 at 20:19
-
And what if I want the ticks and labels both left and right? Commented Feb 16, 2018 at 16:59
-
3I did not sort out why, but this breaks if you have subplots with
sharey=True
. Commented May 3, 2018 at 18:41 -
What's the command to make the ticks appear on the left and the right? Thanks! Commented Aug 2, 2018 at 5:57
For right labels use ax.yaxis.set_label_position("right")
, i.e.:
f = plt.figure()
ax = f.add_subplot(111)
ax.yaxis.tick_right()
ax.yaxis.set_label_position("right")
plt.plot([2,3,4,5])
ax.set_xlabel("$x$ /mm")
ax.set_ylabel("$y$ /mm")
plt.show()
joaquin's answer works, but has the side effect of removing ticks from the left side of the axes. To fix this, follow up tick_right()
with a call to set_ticks_position('both')
. A revised example:
from matplotlib import pyplot as plt
f = plt.figure()
ax = f.add_subplot(111)
ax.yaxis.tick_right()
ax.yaxis.set_ticks_position('both')
plt.plot([2,3,4,5])
plt.show()
The result is a plot with ticks on both sides, but tick labels on the right.
Just is case somebody asks (like I did), this is also possible when one uses subplot2grid. For example:
import matplotlib.pyplot as plt
plt.subplot2grid((3,2), (0,1), rowspan=3)
plt.plot([2,3,4,5])
plt.tick_params(axis='y', which='both', labelleft='off', labelright='on')
plt.show()
It will show this:
-
5This works with
ax.tick_params(axis='y', which='both', labelleft='off', labelright='on')
as well. But it does not move theylabel
– EricCommented Aug 5, 2016 at 0:41 -
3Well you can always use
plt.gca()
to get the current axes object. Therefore you would use:plt.gca().yaxis.set_label_position("right")
– sannajCommented May 8, 2019 at 15:00 -
labelleft, labelright : bool
. So it should beplt.tick_params(axis='y', which='both', labelleft=False, labelright=True)
to disable left-side labels. Alsoleft=False, right=True
to move ticks as well. Commented Feb 17, 2021 at 1:50
Using subplots and if you are sharing the y-axis (i.e., sharey=True
), before creating the plot, try:
plt.rcParams['ytick.right'] = plt.rcParams['ytick.labelright'] = True
plt.rcParams['ytick.left'] = plt.rcParams['ytick.labelleft'] = False
From: Matplotlib gallery
-
Works neatly in 2022 with current version of matplotlib. Commented Nov 27, 2022 at 20:49