我想批量创建一些 matplotlib 图,然后以交互方式显示它们,例如像这样的东西? (当前代码不显示绘图)
import matplotlib.pyplot as plt
from ipywidgets import interact
plots = {'a': plt.plot([1,1],[1,2]), 'b': plt.plot([2,2],[1,2])}
def f(x):
return plots[x]
interact(f, x=['a','b'])
最佳答案
重绘图形
可能你想要这样的东西,在每次新选择时清除图形,并将相关艺术家重新添加到 Canvas 。
%matplotlib notebook
import matplotlib.pyplot as plt
from ipywidgets import interact
plots = {'a': plt.plot([1,1],[1,2]), 'b': plt.plot([2,2],[1,2])}
def f(x):
plt.gca().clear()
plt.gca().add_artist(plots[x][0])
plt.gca().autoscale()
plt.gcf().canvas.draw_idle()
interact(f, x=['a','b']);
在 jupyter notebook 中的结果:
block 传输
不幸的是,当前的笔记本后端does not support blitting .使用 block 传输,可以预先构建绘图,然后将它们 block 传输到轴上。这可能看起来像这样:
import matplotlib.pyplot as plt
from matplotlib.widgets import RadioButtons
fig, ax = plt.subplots()
fig.subplots_adjust(left=0.18)
line1, = ax.plot([1,1],[1,2])
line2, = ax.plot([2,2],[1,2], color="crimson")
line2.remove()
fig.canvas.draw()
# store state A, where line1 is present
stateA = fig.canvas.copy_from_bbox(ax.bbox)
line1.remove()
ax.add_artist(line2)
fig.canvas.draw()
# store state B, where line2 is present
stateB = fig.canvas.copy_from_bbox(ax.bbox)
plots = {'a': stateA, 'b': stateB}
rax = plt.axes([0.05, 0.4, 0.1, 0.15])
check = RadioButtons(rax, ('a', 'b'), (False, True))
def f(x):
fig.canvas.restore_region(plots[x])
check.on_clicked(f)
plt.show()
上面的代码在一个普通的交互式图形中运行良好。一旦 matplotlib 的某些 future 版本在笔记本后端中支持 blitting,就可以替换 RadioButtons
并在笔记本中使用 interact
。
关于python - 你能 "cache"matplotlib 图并动态显示它们吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48632614/