chemist
chemist

Reputation: 373

How to update plotly plot in offline mode (Jupyter notebook)

I would like to build a simple interface with plotly and ipywidgets inside Jupyter Notebook (offline mode) and I am wondering how to update the plot if I want to add extra data. Here is my code:

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)

Any comments/suggestions are highly appreciated.

Upvotes: 3

Views: 3174

Answers (1)

tags
tags

Reputation: 4059

Crazy how everyone seem to be confused about interacting with offline plotly charts!

Still it is fairly simple taking benefit of property assignment (e.g. see this documentation although it is now partly deprecated).

The naive snippet example below updates a plotly.graph_objs.FigureWidget() as user interacts via a dropdown widget. In fact, the pandas.DataFrame() containing the xaxis and yaxis data of the chart is sliced along a Commodity dimension the user wants to display the line chart of.

The most tedious part probably is getting all additional library requirements set if you are using 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]))

Upvotes: 2

Related Questions