barbarab
barbarab

Reputation: 47

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. 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!

Upvotes: 1

Views: 583

Answers (1)

baccandr
baccandr

Reputation: 1130

As pointed out in the comments ax.secondary_yaxis cannot handle the output of your function, which is an array with n elements. The third example here provides a clever way to address this issue by using the numpy interpolation function. 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))

Here the result: enter image description here

Please note that, as explained in the example, the mapping functions need to be defined beyond the nominal plot limits.

Upvotes: 2

Related Questions