Reputation: 5408
My question is related to this SO post. However, I do not want to use interact but rather I would like to call iplot with a button. Unfortunately, the plot is shown multiple times in the same cell. Any ideas how to avoid that ?
#%matplotlib inline
from matplotlib import pyplot as plt
import numpy as np
import ipywidgets as widgets
import plotly.plotly as ply
import plotly.graph_objs as go
from plotly.widgets import GraphWidget
from plotly.offline import init_notebook_mode, iplot, plot
init_notebook_mode(connected=True)
#%%
def plotly_kin(x, y, color_list):
""" A generic plot function for x,y line plots
"""
# pop the first item from the colormap
try:
color = color_list.pop(0)
except AttributeError:
# reameke the colormap
color_list = list(plt.cm.tab10.colors)
color = color_list.pop(0)
# create a line object
line = go.Scatter(x=x, y=y, mode='scatter', name='test')
# make a data object
traces.append(line)
iplot(traces, show_link=False)
#%%
traces = []
#%% this part works just fine
x = np.arange(0,10)
y = np.random.normal(size=len(x))
plotly_kin(x, y, 'a')
The output is always in the same graph:
However, this part does not work because the figure is appended to the cells output:
def test_plot(message):
x = np.arange(0,10)
y = np.random.normal(size=len(x))
plotly_kin(x, y, 'a')
button_test = widgets.Button(description='test')
button_test.on_click(test_plot)
display(button_test)
Upvotes: 1
Views: 759
Reputation: 15941
The problem is that clicking the button does not clear the previous output of the cell. If you were using matplotlib
, this could be solved by creating the figure and axes first and only updating the data on button click, but I don't think that is possible with plot.ly
.
You can instead use the notebook's own API to remove the existing cell output when you click the button. This will also delete the button, so at the end of the button code you need to recreate the button.
from IPython.display import clear_output
def test_plot(message):
clear_output()
x = np.arange(0,10)
y = np.random.normal(size=len(x))
plotly_kin(x, y, 'a')
create_button()
def create_button():
button_test = widgets.Button(description='test')
button_test.on_click(test_plot)
display(button_test)
create_button()
Upvotes: 1