Home > database >  Create a scaled secondary y-axis in Matplotlib
Create a scaled secondary y-axis in Matplotlib

Time:09-22

The objective is to plot a scatter plot and create secondary y-axis. Here, the secondary y-axis is just scaled copy of the original scatter plot.

Assume the scaling can be calculated y2=y1/2.5

where, y1 and y2 is the y axis from the scatter plot,and scaled copy of the original scatter plot, respectively.

This can be visualized as below.

enter image description here

However, using the code below,

import numpy as np
import matplotlib.pyplot as plt
x, y = np.random.random((2,50))

fig, ax1 = plt.subplots()

ax1.scatter(x, y*10, c='b')

ax2 = ax1.twinx()
y2=y/2.5
ax2.plot(1, 1, 'w-')
ax1.set_xlabel('X1_z')
ax1.set_ylabel('x1_y', color='g')
ax2.set_ylabel('x2_y', color='r')

which produced

enter image description here

There are three issues

  • The secondary y-axis is not scaled properly
  • As expected but not intended the existence multiple horizontal line root from the secondary y-axis
  • Is there a possible way to create the scaled y-axis without the need of the line ax2.plot(1, 1, 'w-')

May I know how to handle this?

CodePudding user response:

As suggested in the comment, using secondary_yaxis

x, y = np.random.random((2,50))
fig, ax = plt.subplots()
ax.scatter(x, y*10, c='b')
ax.set_xlabel('X1_z')
ax.set_ylabel('x1_y')
ax.set_title('Adding secondary y-axis')
def a2b(y):
    return y/2.5
def b2a(y):
    return 2.5*y
secax = ax.secondary_yaxis('right', functions=(a2b,b2a))
secax.set_ylabel('x2_y')
plt.show()

Produced

enter image description here

  • Related