how to add a second y axis on the right matplotlib in python

You can create a plot with two y-axes in Matplotlib by creating a twinx axes object. Here's an example:

main.py
import matplotlib.pyplot as plt

fig, ax1 = plt.subplots()

# plot some data on ax1
ax1.plot(x, y1, 'b-')
ax1.set_xlabel('X axis')
ax1.set_ylabel('Y axis 1', color='b')

# create a second y-axis on ax1
ax2 = ax1.twinx()

# plot some data on ax2
ax2.plot(x, y2, 'r-')
ax2.set_ylabel('Y axis 2', color='r')

plt.show()
317 chars
18 lines

In this example, ax1 is the primary y-axis, and ax2 is the secondary y-axis. ax2 is created by calling ax1.twinx(). You can then plot data on ax2 using the standard plot() function.

Make sure to specify the color argument to set the y-axis labels to different colors, since the default is blue for both.

related categories

gistlibby LogSnag