matplotlib事件出现问题(不显示图)

6tqwzwtp  于 2022-11-30  发布在  其他
关注(0)|答案(1)|浏览(108)

documentation中关于事件处理,我们有一个有趣的例子(“Picking exercise”)
我对类似的东西很感兴趣,但不是每次在第一个窗口中拾取一个点时都会出现一个新窗口(就像现在一样),我想改变同一个第二个窗口的图。
所以我做了

"""
Compute the mean and stddev of 100 data sets and plot mean vs. stddev.
When you click on one of the (mean, stddev) points, plot the raw dataset
that generated that point.
"""

import numpy as np
import matplotlib.pyplot as plt

X = np.random.rand(100, 1000)
xs = np.mean(X, axis=1)
ys = np.std(X, axis=1)

fig, ax = plt.subplots()
ax.set_title('click on point to plot time series')
line, = ax.plot(xs, ys, 'o', picker=True, pickradius=5)  # 5 points tolerance

figR, axsR = plt.subplots()

def onpick(event):
    if event.artist != line:
        return
    n = len(event.ind)
    if not n:
        return
    print("Index ",event.ind)
    
    
    axsR.plot(X[event.ind])
    axsR.set_ylim(-0.5,1.5)
    
    # fig, axs = plt.subplots(n, squeeze=False)
    # print(axs.flat)
    # for dataind, ax in zip(event.ind, axs.flat):
    #     ax.plot(X[dataind])
    #     ax.text(0.05, 0.9,
    #             f"$\\mu$={xs[dataind]:1.3f}\n$\\sigma$={ys[dataind]:1.3f}",
    #             transform=ax.transAxes, verticalalignment='top')
    #     ax.set_ylim(-0.5, 1.5)
    figR.show()
    return True

fig.canvas.mpl_connect('pick_event', onpick)
plt.show()

所以现在我有两个窗口,在一个窗口中我可以清楚地选择,但另一个窗口没有显示我希望的情节。我如何才能使情节出现?
最奇怪的事情发生了
在使用python 3.8.12 matplotlib 3.5.1的conda环境中,它可以正常工作。
在另一个与python 3.7.10 matplotlib 3.3.4不工作

mdfafbf1

mdfafbf11#

我已经对你的代码做了一个小测试,把你的onpick函数的最后一行改为figR.canvas.draw()就可以解决这个问题了,函数应该看起来像:

def onpick(event):
    if event.artist != line:
        return
    n = len(event.ind)
    if not n:
        return
    print("Index ",event.ind)
    
    axsR.plot(X[event.ind])
    axsR.set_ylim(-0.5,1.5)
    
    figR.canvas.draw()
    return True

draw()将重新绘制图形。这允许您在交互模式下工作,如果您更改了数据或设置了图形格式,则允许图形本身更改。

相关问题