如何使用Jupyter Notebook使用ipywidgets高效地显示类似的绘图?
我希望交互式地绘制一个重绘图(重绘图是因为它有很多数据点,绘制它需要一些时间),并使用ipywidgets中的interact修改其中的单个元素,而无需重新绘制所有复杂的绘图。有没有内置的功能可以做到这一点?
基本上我想做的是
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秒。我希望有一些方法可以让图形保持在那里,而只是替换那个矩形。
一个技巧是创建一个常量部分的图形,使其成为绘图的背景,然后只绘制矩形部分。但是听起来太下流了
谢谢
发布于 2016-07-22 22:47:14
这是一个更改矩形宽度的交互式方法的粗略示例(我假设您使用的是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是新坐标。
https://stackoverflow.com/questions/38528426
复制相似问题