在 Matplotlib 中创建缩放的辅助 y 轴

Create a scaled secondary y-axis in Matplotlib

objective 是绘制散点图并创建次要 y 轴。在这里,第二个 y 轴只是原始散点图的缩放副本。

假设可以计算缩放比例 y2=y1/2.5

其中,y1y2 分别是散点图的 y 轴,以及原始散点图的缩放副本。

这可以如下图所示。

但是,使用下面的代码,

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')

产生了

存在三个问题

我可以知道如何处理吗?

按照评论中的建议,使用 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()

已制作