我想在Jupyter Notebook(离线模式)中使用plotly和ipywidgets构建一个简单的界面,我想知道如果我想添加额外数据如何更新绘图。这是我的代码:
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)
我们非常感谢您提出任何意见/建议。
答案 0 :(得分:2)
每个人似乎都对与离线绘图表交互感到困惑!
利用属性分配仍然非常简单(例如,尽管现在已部分弃用了此documentation,但还是不推荐使用)。
下面的幼稚代码段示例在用户通过plotly.graph_objs.FigureWidget()
小部件进行交互时更新了dropdown
。实际上,包含图表的x轴和y轴数据的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]))