我想批量创建一些 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'])
Run Code Online (Sandbox Code Playgroud)
也许您想要这样的东西,其中每个新选择的图形都会被清除,并且相关艺术家会被读取到画布上。
%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']);
Run Code Online (Sandbox Code Playgroud)
Jupyter 笔记本的结果:
不幸的是,笔记本后端目前不支持 blitting。使用位块传送,我们可以预先构建绘图,然后将它们位块传送到轴上。这可能看起来像这样:
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()
Run Code Online (Sandbox Code Playgroud)
上面的代码在正常的交互式图形中运行良好。一旦 matplotlib 的某些未来版本的笔记本后端支持位块传输,就可以在笔记本中替换RadioButtons并使用。interact