我想在Jupyter Notebook(离线模式(中使用plotly和ipywidgets构建一个简单的界面,如果我想添加额外的数据,我想知道如何更新plot。这是我的代码:
import plotly
from plotly.offline import iplot
from plotly.graph_objs import graph_objs as go
import ipywidgets as widgets
from IPython.display import display
plotly.offline.init_notebook_mode(connected=True)
trace_high = go.Scatter(
x=[1,2,3,4],
y=[4,6,2,8],
name = "High",
line = dict(color = '#7F7F7F'),
opacity = 0.8)
data = [trace_high]
def plot_extra_data(drop):
if drop["new"] == "2":
trace_low = go.Scatter(
x=[1,2,3,4],
y=[1,7,3,5],
name = "Low",
line = dict(color = 'green'),
opacity = 0.8)
data.append(trace_low)
fig.update(data=data)
drop = widgets.Dropdown(
options=['1', '2', '3'],
value='1',
description='Number:',
disabled=False,
)
drop.observe(plot_extra_data, "value")
display(drop)
fig = dict(data=data)
iplot(fig)
任何意见/建议将不胜感激。
疯狂的是,每个人似乎都对与离线情节图表的交互感到困惑!
利用属性分配仍然相当简单(例如,请参阅此文档,尽管它现在已部分弃用(。
下面的朴素代码段示例在用户通过dropdown
小部件进行交互时更新plotly.graph_objs.FigureWidget()
。实际上,包含图表的轴和 yaxis 数据的pandas.DataFrame()
是沿着用户希望显示折线图的Commodity
维度切片的。
最繁琐的部分可能是设置所有其他库要求(如果您使用的是jupyterlab
import pandas as pd
import plotly.graph_objs as go
import ipywidgets as widgets
df = pd.DataFrame({'cmdty' : ['beans', 'beans', 'beans', 'corn', 'corn', 'corn'],
'month' : [1, 2, 3, 1, 2, 3],
'value' : [10.5, 3.5, 8.0, 5.0, 8.75, 5.75]})
items = df.cmdty.unique().tolist()
cmdty = widgets.Dropdown(options=items,
description='Commodity')
def response(change):
c = cmdty.value
df_tmp = df[df.cmdty == c]
x0 = df_tmp['month'] # Useless here as x is equal for the 2 commodities
x1 = df_tmp['value']
fig.data[0].x = x0 # Useless here as x is equal for the 2 commodities
fig.data[0].y = x1
fig = go.FigureWidget(data=[{'type' : 'scatter'}])
cmdty.observe(response, names='value')
display(widgets.VBox([cmdty, fig]))