How to plot yticks on right side and keep the classic left side

Viewed 421

I want to plot some data and add a ytick on it on the right side but when I am doing it, the left side ticks disappear and i want to keep it. Can someone help me please ? I have seen other posts on this but they are all using ax. commands and I am not familiar with this, I am only using plt. functions.

I used these commands:

plt.yticks([seuil1,seuil2],["20%","20%"])
plt.tick_params(axis='y',labelleft=False,labelright=True)

Plot without yticks: Plot without yticks

Plot with yticks right side: Plot with yticks right side

As you can see, the left side disappeared.

2 Answers

On the difference between using plt and ax these are two different styles of using matplotlib; they are pyplot and object-oriented styles respectively.

With pyplot-style matplotlib creates and manages the figures and axes, you use plt. functions to manipulate them.

With object-oriented style you explicitly create your figure and axes (fig, ax = plt.subplots()) and then call methods on either the fig or ax to manipulate them. This is the approach I have taken in my example.

Take a look at the matplotlib usage guide and their tutorials to get an idea of how you can create and customise your plots.


Here you want to use twinx to create another axis that shares the x-axis allowing you to position other yticks on the right y-axis. I have commented above each line with what it is that line is doing.

# Create a figure and ax
fig, ax = plt.subplots()

# Get data
x = np.linspace(0, 10, 101)
y = 1 / x

# Plot the data
ax.plot(x, y, label=r"$f(x)=\frac{1}{x}$")
# Place legend
ax.legend(loc="upper right")

# Create a second y-axis
y2 = ax.twinx()
# Copy the y limits from the left axis
y2.set_ylim(ax.get_ylim())
# Set the right y-yick positions
y2.set_yticks([2, 6])
# Set the right y-tick labels
y2.set_yticklabels(["A", "B"])

Which produces:

Graph of y = 1/x with right tick labels

In addition to @Alex answer...

If you don't need ticks, try:

import matplotlib.pyplot as plt
import numpy as np
# Create a figure and ax
fig, ax = plt.subplots()

# Get data
x = np.linspace(0, 10, 101)
y = 1 / x

# Plot the data
ax.plot(x, y, label=r"$f(x)=\frac{1}{x}$")

vals = [2, 6]
labs = ['A', 'B']
for val, lab in zip(vals, labs):
    ax.text(1.02, val, lab, transform=ax.get_yaxis_transform())

plt.show()

If you do need ticks, rather than making a twin axes you can also create a secondary axes:

import matplotlib.pyplot as plt
import numpy as np
# Create a figure and ax
fig, ax = plt.subplots()

# Get data
x = np.linspace(0, 10, 101)
y = 1 / x

# Plot the data
ax.plot(x, y, label=r"$f(x)=\frac{1}{x}$")

vals = [2, 6]
labs = ['A', 'B']

secax = ax.secondary_yaxis(1.0)
secax.set_yticks(vals)
secax.set_yticklabels(labs)

plt.show()
Related