python - 如何在 Jupyter 笔记本中重绘 matplotlib.pyplot 图?
问题描述
我根本无法让我的 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()
解决方案
知道了。使用轴的句柄,然后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)
推荐阅读
- c++ - C++获取重载成员函数指针的常用方法
- android - 保存对 Application 实例的引用会导致内存泄漏吗?
- r - 在不复制的情况下交换两个 SEXP
- django - 允许一个对象一次选择 ManyToMany 中的选项
- ruby - Ruby 和 ActiveRecord 初始化
- swift - 使用 UIGraphicsImageRenderer 图像检索像素数据无法正常工作
- curl - curl和wsdl的区别
- amazon-web-services - AWS S3 存储桶策略访问被拒绝
- java - 更新和旧项目后 Android Studio 出现问题
- mongodb - QueryDSL 与 Spring Data MongoDB - 包含所有