[英]Python - plot with secondary axis - function with 2 variables
I've quickly skimmed old questions but didn't find this specific one.我很快浏览了旧问题,但没有找到这个具体的问题。 Sorry if it's a duplicate!对不起,如果它是重复的!
I'm trying to plot a secondary axis, with ax.secondary_yaxis(), in which the function that connects the two axes involves an additional variable.我正在尝试使用 ax.secondary_yaxis() 绘制辅助轴,其中连接两个轴的函数涉及一个附加变量。 This is my example:这是我的例子:
x = np.linspace(0, 50, 100)
y = np.linspace(220, 273, 100)
k = np.linspace(-10, 10, 100)
def y_to_y2(y):
return y * k
def y2_to_y(y2):
return y2 / k
fig, ax = plt.subplots()
ax2 = ax.secondary_yaxis("right", functions=(y_to_y2, y2_to_y))
ax.plot(x, y)
But I get this error:但我收到此错误:
ValueError: operands could not be broadcast together with shapes (2,) (100,)
Thanks a lot for your help and suggestions!非常感谢您的帮助和建议!
As pointed out in the comments ax.secondary_yaxis
cannot handle the output of your function, which is an array with n elements.正如评论中指出的那样ax.secondary_yaxis
无法处理您的函数的输出,它是一个包含 n 个元素的数组。 The third example here provides a clever way to address this issue by using the numpy interpolation function. 此处的第三个示例通过使用 numpy 插值函数提供了一种巧妙的方法来解决此问题。 Your specific case could be solved by doing something like this:您的具体情况可以通过执行以下操作来解决:
x = np.linspace(0, 50, 100)
y = np.linspace(220, 273, 100)
k = np.linspace(-10, 10, 200)
yold = np.linspace(210, 283, 200)
ynew = yold*k
def forward(y):
return np.interp(y, yold, ynew)
def inverse(y):
return np.interp(y, ynew, yold)
fig, ax = plt.subplots()
ax.plot(x, y)
ax2 = ax.secondary_yaxis("right", functions=(forward, inverse))
Please note that, as explained in the example, the mapping functions need to be defined beyond the nominal plot limits.请注意,如示例中所述,映射函数需要定义为超出标称绘图限制。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.