首页 > 解决方案 > 在另一个图中按下按钮时自动更新图

问题描述

我在 pyplot 中创建了一个图形,并为其分配了一个回调,该回调应该调用另一个图形的更新。但是,直到我在 PyCharm Python 控制台中键入一些任意命令,它才会更新。

代码片段:

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

单击标题为“单击此处”的轴不会在另一个图形中产生变化,除非我在 PyCharm 控制台中写了一些东西 - 可以是任何东西,比如 i = 2。

如何在第二个图中按下按钮时自动更新第一个图?我尝试按照此处此处的说明添加 plt.draw()、plt.pause(.)但无济于事。

版本:
Pycharm 2021.2.2 社区版
Python 3.8
Windows 10 Enterprise 10.0.18363

标签: pythonmatplotlibcallbackpycharm

解决方案


推荐阅读