Home > Net >  Problem with matplotlib events (plot does not appear)
Problem with matplotlib events (plot does not appear)

Time:11-29

In the documentation about event handling, we have an interesting example (the "Picking excercise")

I am interested in something similar but instead of a new window appearing every time a point is picked in the first window (as it is now) I would like to change the plot of the same second window.

So I did

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

So now I have two windows, and in one I can clearly pick but the other window does not show the plot I wish. How can I make that the plot appears?

EDIT: The strangest thing happened

In a conda environment with python 3.8.12 matplotlib 3.5.1 it is working
In another with python 3.7.10 matplotlib 3.3.4 it is not working

CodePudding user response:

I have made small test on your code, changing the last line of your onpick function to figR.canvas.draw() solve the issue for me, the function should look like:

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() will re-draw the figure. This allows you to work in interactive mode an in case you have changed your data or formatted the figure, allow the graph itself to change.

  • Related