简体   繁体   中英

How do I redraw a matplotlib.pyplot figure in a Jupyter notebook?

I simply cannot get my Jupyterlab chart to redraw, and I have no idea why. I've tried combinations of clear_output , and canvas.draw() and canvas.flush_events() . What am I doing wrong?

from IPython.display import clear_output
import matplotlib.pyplot as plt
%matplotlib inline

# Matplotlib chart wrapper that can update itself. Is a 1-dimensional plot of dots.
class Chart:

    def __init__(self, values):
        self.values = [v for v in values]
        self.fig = plt.figure()
        self.axes = self.fig.add_subplot(111)
        self.axes.get_yaxis().set_visible(False)
        self.line, = self.axes.plot(values, [1 for v in range(len(values))],\
            color="gray", marker="o", linestyle="none", markersize=10) # returns a tuple, hence the comma
        self.axes.xaxis.label.set_text("Weight (g)")
        plt.show()

    def update(self, index, value):
        print("received {} at index {}".format(value, index))
        self.values[index] = value
        self.line.set_ydata(self.values)
        clear_output(wait=True)
        self.fig.canvas.draw()
        self.fig.canvas.flush_events()

c = Chart([10.2, 8.9, 11.3, 12, 9.9, 10.5])
c.update(2,8)

This code should remove the point at 11.3 and replace it with 8 . I do wonder if self.fig.show() would make more sense (as I have several figures in a notebook, and eventually calling plt.show() will be unmanageable without specifying the fiture). However, I get the following error if I try that:

UserWarning: Matplotlib is currently using module://ipykernel.pylab.backend_inline, which is a non-GUI backend, so cannot show the figure. % get_backend()

Got it. Use a handle to the Axes, and call cla() then plot() .

import matplotlib.pyplot as plt
import time
%matplotlib inline
fig = plt.figure()
axes = fig.add_subplot(111)

hfig = display(fig, display_id=True)
values = [1,2,3,4,5,6]

def draw():
    #fig.clf()
    axes.plot(values, [v*v for v in values])
    fig.canvas.draw()
    hfig.update(fig)
    time.sleep(1)

def update():
    print(str(values))
    axes.cla()
    axes.plot(values, [v*(v+1) for v in values])
    fig.canvas.draw()
    hfig.update(fig)

draw()
time.sleep(1)
update()
plt.close(fig)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM