1

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!

2
  • 4
    The y inside the y_to_y2 is not the same y as defined in the beginning of your code. Try to add a print(y) statement inside the function. It is a list of size two, hence the error. Have a look at the examples in the matplotlib secondary_yaxis docs to understand what transformations this can do. Commented Jul 15, 2021 at 15:02
  • also, this is the reason it's important to post (and read) the full traceback of your error Commented Jul 15, 2021 at 15:16

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.