【问题标题】:How do I redraw a matplotlib.pyplot figure in a Jupyter notebook?如何在 Jupyter 笔记本中重绘 matplotlib.pyplot 图?
【发布时间】:2021-07-27 15:50:16
【问题描述】:

我根本无法让我的 Jupyterlab 图表重绘,我也不知道为什么。我尝试了clear_output、canvas.draw() 和canvas.flush_events() 的组合。我做错了什么?

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)

此代码应删除11.3 处的点并将其替换为8。 我确实想知道self.fig.show() 是否更有意义(因为我的笔记本中有几个数字,如果不指定设备,最终调用plt.show() 将无法管理)。但是,如果我尝试这样做,我会收到以下错误:

UserWarning: Matplotlib 当前使用的是 module://ipykernel.pylab.backend_inline,这是一个非 GUI 后端,所以无法显示图。 % get_backend()

【问题讨论】:

  • this exemple 有什么帮助吗?
  • @krassowski 不幸的是没有。我的代码中可能缺少一行可以使图形正确重绘,但我不知道它会是什么。

标签: python matplotlib jupyter jupyter-lab


【解决方案1】:

知道了。使用轴的句柄,然后调用cla() 然后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)

【讨论】:

    猜你喜欢
    • 2022-07-21
    • 2015-10-15
    • 2016-10-10
    • 1970-01-01
    • 2017-08-23
    • 1970-01-01
    • 2019-03-17
    • 2021-03-22
    • 2016-07-04
    相关资源
    最近更新 更多