我想批量创建一些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'])
答案 0 :(得分:2)
可能你想要这样的东西,在每个新的选择上清除数字,并将相关的艺术家读回画布。
%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笔记本:
不幸的是,笔记本后端目前是does not support blitting。使用blitting,可以在prehands之前构建绘图,然后将它们blit到轴。这看起来像这样:
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的某个未来版本的笔记本后端支持blitting时,可以在笔记本中替换RadioButtons
并使用interact
。