question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

partial update of dcc.Graph.figure with LiveGraph composite object

See original GitHub issue

(probably this feature would not be implemented in dcc directly, but I’m posting this feature request here because this is the closest repo)

At the moment, when users want to update a small part of a plotly figure in a dcc.Graph in their app, they have two choices:

  • either have the whole dcc.Graph.figure as Output, which can result in passing large objects over the network and poor performance for traces with a lot of data
  • update only a dcc.Store, and update the dcc.Graph in a clientside callback. This is fast, but this means that users have to write Javascript, which is a shame for a coding pattern which is quite common.

We could instead provide an object which would have:

  • two component members: a Store (corresponding to a patch) and a Graph
  • an app member
  • and a clientside callback updating the Graph with the Store which would be attached to the app when creating the object

The user-facing API could look like

import dash_core_components as dcc
import dash_html_components as html
import dash
from dash.dependencies import Input, Output, State
import plotly.express as px
from dash_partial_update import LiveGraph
import numpy as np

app = dash.Dash(__name__)
fig = px.imshow(np.random.randint(255, size=(1000, 1000, 3)).astype(np.uint8))

# define app to attach clientside callbacks to it
graph, upstream_graph = LiveGraph(app=app)
graph.figure = fig

app.layout = html.Div([
    graph,
    upstream_graph,
    dcc.Dropdown(id='dropdown', values=['red', 'blue', 'yellow'])
    ])

@app.callback(
    Output(upstream_graph.id, 'patch'),
    [Input('dropdown', 'values')]
)
def update_dropdown(value):
    patch = dict(layout=dict(newshape=dict(color=value)))
    return patch

It would not be possible to target the dcc.Graph.figure as Output since it would already be used in an internal callback, but figure or selectedData could still be used as Input or State. Documentation should be written to illustrate these different cases.

Probably this component should be implemented as a standalone package as a first step, but I’m hoping that the dcc devs can chime in here and make suggestions 😃.

This development will probably be part of the CZI project on image processing.

Issue Analytics

  • State:open
  • Created 3 years ago
  • Comments:6 (6 by maintainers)

github_iconTop GitHub Comments

6reactions
nicolaskruchtencommented, Nov 18, 2020

Here’s a working version of the approach outlined above:

import dash
from jupyter_dash import JupyterDash
import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import Input, Output
import plotly.express as px
import plotly.graph_objects as go

figure = px.scatter(px.data.iris(), x="sepal_length", y="sepal_width")

app = JupyterDash(__name__)

app.layout = html.Div(children = [
  dcc.Store(id="figstore", data=figure),
  dcc.Store(id="patchstore", data={}),
  dcc.Store(id="patchstore2", data={}),
  dcc.Dropdown(id="color", value="red",
              options=[{"label":x, "value":x} for x in ["red", "blue"]]),
  dcc.Dropdown(id="linewidth", value=1,
              options=[{"label":x, "value":x} for x in [0,1,2,3]]),
  dcc.Graph(id="graph")
])

deep_merge = """
function batchAssign(patches) {
    function recursiveAssign(input, patch){
        var outputR = Object(input);
        for (var key in patch) {
            if(outputR[key] && typeof patch[key] == "object") {
                outputR[key] = recursiveAssign(outputR[key], patch[key])
            }
            else {
                outputR[key] = patch[key];
            }
        }
        return outputR;
    }

    return Array.prototype.reduce.call(arguments, recursiveAssign, {});
}
"""

app.clientside_callback(
    deep_merge,
    Output('graph', 'figure'),
    [Input('figstore', 'data'), 
     Input('patchstore', 'data'), 
     Input('patchstore2', 'data')]
)

@app.callback(Output('patchstore', 'data'),[Input('color', 'value')])
def cb(color):
    return go.Figure(go.Scatter(marker_line_color=color))

@app.callback(Output('patchstore2', 'data'),[Input('linewidth', 'value')])
def cb(width):
    return go.Figure(go.Scatter(marker_line_width=width))

app.run_server(mode="jupyterlab")
0reactions
alexcjohnsoncommented, Dec 2, 2020

Yes exactly - only of course the combiner component would have the merge logic built in, so instead of the deep_merge callback you’d just have a clientside identity / pipe callback connecting the combiner’s output prop (result?) to graph.figure

One consequence of this approach, which may or may not be desirable (and is NOT the case with the deep_merge callback approach @emmanuelle used above): none of these callbacks would be part of the same callback chain since the connection would be made internally by the component. This might mean that we’d fire the final result->graph.figure callback once per patch, if several patches were provided simultaneously by different callbacks, rather than waiting for them all to arrive, but I think we could avoid that by having the combiner look at its loading state and only do the combining when it’s done loading. But also it would be possible to use this component to hide a circular callback dependency - leading to a potential infinite loop that would be hard for the renderer to detect. I’m sure some users would be happy to use this as a generic workaround when they need a circular dependency, but it would be dangerous in general.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Live Updates | Dash for Python Documentation | Plotly
This example pulls data from live satellite feeds and updates the graph and the text every second. import datetime import dash from dash...
Read more >
Live Graphs - Data Visualization GUIs with Dash and Python p.4
In this tutorial, we're going to be create live updating graphs with Dash and Python. Live graphs can be ... Graph(id='live-graph', animate=True), dcc....
Read more >
Dash: updating a figure's data instead of updating graph's ...
Div([ dcc. ... Input('my_input', 'value')) def update_live_graph(value): data ... But returning Figures is usually less wordy than this, ...
Read more >
Plot Live Graphs using Python Dash and Plotly - GeeksforGeeks
Div( [ dcc.Graph(id = 'live-graph', animate = True), dcc.Interval( id = 'graph-update', interval = 1000, n_intervals = 0 ), ] ).
Read more >
Data Visualization GUIs with Dash and Python p.4 - YouTube
How to create live graphs in Python with Dash, the browser-based data visualization application framework.Text tutorials and sample code: ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found