首页 > 解决方案 > In Jupyter Notebook and matplotlib, how to avoid replot everything in an interactive plot

问题描述

In jupyter notebook, have a plot side by side with another animation. For each frame of the animation, the plot should update with a vertical line and a red dot showing the value of that property. A minimal working example (without the animation) is below:

import ipywidgets as wg
import matplotlib.pyplot as plt

class interactive_plot:

    def __init__(self,r):
        self.X = [x for x in range(r)]
        self.Y = [y for y in range(r)]
        self.r = r
        self.fig = None
        self.ax = None

    def pathPlot(self, xframe = None):

        if self.fig is None:
            self.fig = plt.figure()
            self.ax =self.fig.add_subplot(1,1,1)
            self.ax.plot(self.X, self.Y, 'bo-')

        else:
            self.fig = plt.gcf()
            self.ax = plt.gca()
            self.ax.plot(self.X, self.Y, 'bo-')

        if xframe is not None:
            self.ax.axvline(x = self.X[xframe],color = 'black',linestyle = '--')
            self.ax.plot(self.X[xframe],self.Y[xframe], 'ro', markersize=10)

    def pathPlay(self):

        frame = wg.IntSlider(min = 0, max = self.r - 1)
        wg.interact(self.pathPlot, xframe = frame)

test = interactive_plot(10)
test.pathPlay()

This minimal example works "fine". However, in my jupyter notebook there is another animation side by side with this, and as the number of animations increase, perfomance is an issue (One may see the plot being cleared and reploted).

I thought that maybe I could avoid the line self.ax.plot(self.X, self.Y, 'bo-') under the else statement (substituting with a self.fig.show()) and just update the vertical line with the red dot. However, I could not make this. Everytime, the blue line goes away and I get only the vertical line and the red dot in the plot.

So I was wondering:

1- What is the correct way to just update a plot?

2- Will I really get a performance enhancement? At least I won't see the plot being cleared and reploted, right?

标签: pythonpython-3.xmatplotlibjupyter-notebookpython-2.x

解决方案


推荐阅读