0

I have created a figure in pyplot, and assigned a callback to it that should invoke the update of another figure. However it does not update until I type some arbitrary command in the PyCharm Python console.

Code snippet:

import matplotlib.pyplot as plt

def onclick(event):
    global sign
    sign *= -1
    ax.cla()
    x2 = [i for i in range(10)]
    y2 = [i*sign for i in range(10)]
    ax.plot(x2, y2)
    plt.show()
    print("Done")

global sign
sign = 1
ax = plt.figure().add_subplot()
ax.set_title("Toggles slope on click in other figure")
fig = plt.figure()
ax2 = fig.add_subplot()
x = [i for i in range(10)]
y = x
ax2.plot(x, y)
ax2.set_title("Click here")
cid = fig.canvas.mpl_connect('button_press_event', onclick)
plt.show()

Clicking in the axes titled "Click here" does not produce a change in the other figure, unless I write something in the PyCharm console - could be anything, like i = 2.

How do I update the first figure automatically on button press in the second figure? I have tried adding plt.draw(), plt.pause(.) as indicated here and here but to no avail.

Versions:
Pycharm 2021.2.2 Community Edition
Python 3.8
Windows 10 Enterprise 10.0.18363

HaMo
  • 130
  • 1
  • 2
  • 8
  • 1
    PyCharm is specified, but does the desired interactive **action** work with any other IDE? – Trenton McKinney Nov 08 '21 at 10:03
  • You have a typo. In `onclick` it must be `plt.draw()`, not `plt.show()`. After that change, the code works and it's not a PyCharm issue. See [code and plot](https://i.stack.imgur.com/omOIg.png) – Trenton McKinney Nov 08 '21 at 10:39
  • 1
    Does this answer your question? [Updating Matplotlib plot when clicked](https://stackoverflow.com/questions/40434352/updating-matplotlib-plot-when-clicked) – Trenton McKinney Nov 08 '21 at 10:40
  • 1
    Thank you for looking into the issue. Your code works when the subplots have the same parent figure. When you have the axes with the callback in one figure and the axes to be updated in another figure (as in my original example), the problem remains. Thanks to your code I am able to do a workaround (move the axes to the same parent figure), but in order to fix my original question I will have to use some sort of listeners to link different figures to each other I guess. – HaMo Nov 08 '21 at 11:14

0 Answers0