如何使用Jupyter Notebook有效地使用ipywidgets显示类似的图?
我希望以交互方式绘制一个沉重的情节(重要的是它有很多数据点并需要一些时间来绘制它)并使用来自ipywidgets的交互来修改它的单个元素而无需重新绘制所有复杂的绘图。是否有内置功能来执行此操作?
基本上我要做的是
import numpy as np
import matplotlib.pyplot as plt
from ipywidgets import interact
import matplotlib.patches as patches
%matplotlib inline #ideally nbagg
def complicated plot(t):
plt.plot(HEAVY_DATA_SET)
ax = plt.gca()
p = patches.Rectangle(something_that_depends_on_t)
ax.add_patch(p)
interact(complicatedplot, t=(1, 100));
现在每个重绘时间最多需要2秒。我希望有办法保持这个数字,只需替换那个矩形。
黑客将创建一个恒定部分的图形,使其成为绘图的背景,并绘制矩形部分。但声音太脏了
谢谢
答案 0 :(得分:1)
这是一个改变矩形宽度的交互方式的粗略示例(我假设你在IPython或Jupyter笔记本中):
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import ipywidgets
from IPython.display import display
%matplotlib nbagg
f = plt.figure()
ax = plt.gca()
ax.add_patch(
patches.Rectangle(
(0.1, 0.1), # (x,y)
0.5, # width
0.5, # height
)
)
# There must be an easier way to reference the rectangle
rect = ax.get_children()[0]
# Create a slider widget
my_widget = ipywidgets.FloatSlider(value=0.5, min=0.1, max=1, step=0.1, description=('Slider'))
# This function will be called when the slider changes
# It takes the current value of the slider
def change_rectangle_width():
rect.set_width(my_widget.value)
plt.draw()
# Now define what is called when the slider changes
my_widget.on_trait_change(change_rectangle_width)
# Show the slider
display(my_widget)
然后,如果移动滑块,矩形的宽度将会改变。我会尝试整理代码,但你可能有这个想法。要更改坐标,您必须执行rect.xy = (x0, y0)
,其中x0
和y0
是新坐标。