I'm creating an interactive plot which has some lines and annotations etc. A minimum working example is:
def make_plot(scale_factor):
fig = plt.figure(figsize=(8,8)) # create a figure object
ax = fig.add_subplot(1, 1, 1)
x = np.linspace(0,10)
y = np.sin(x)*scale_factor
ax.set_ylim(0,10)
ax.axhline(2,c='k')
plt.plot(x,y)
def make_interactive_plot():
scale_factor_slider = wg.FloatSlider(value=1,
min=0,
max=5,
step=0.1,
description=r'Scaling Factor')
wg.interact(make_plot,
scale_factor = scale_factor_slider)
make_interactive_plot()
This works fine, but as the plot gets more complicated, I'd like to not replot it every time I change a value with a slider. I'd like to just update the Line2D object. This is the common implementation of matplotlib.animation functionality. I'd like to do something like this:
def update_plot(line_obj,scale_factor):
print(scale_factor)
x = np.linspace(0,10)
y = np.sin(x)*scale_factor
line_obj.set_data(x,y)
def make_interactive_plot():
scale_factor_slider = wg.FloatSlider(value=1,
min=0,
max=5,
step=0.1,
description=r'Scaling Factor')
wg.interact(update_plot,
line_obj = line_obj,
scale_factor = scale_factor_slider)
# Initialise plot just once
fig = plt.figure(figsize=(8,8)) # create a figure object
ax = fig.add_subplot(1, 1, 1)
ax.set_ylim(0,10)
ax.axhline(2,c='k')
line_obj, = ax.plot([],[])
make_interactive_plot()
Unfortunately this throws:
ValueError: <matplotlib.lines.Line2D object at 0x7fb1dd3577d0> cannot be transformed to a widget
Does anybody know if modifying an object to update an interactive plot is possible?