PlotlyJS.jl icon indicating copy to clipboard operation
PlotlyJS.jl copied to clipboard

update plot in Dash with asynchronous data

Open mzaffalon opened this issue 4 years ago • 3 comments

I can update the data in a plot using

using PlotlyJS

function data_producer(pl)
    while true
        extendtraces!(pl, Dict(:y => [[randn()]]))
        sleep(1)
    end
end
plt = plot(scatter(; y = randn(10)))
task = @async data_producer(plt)

but the following code using Dash does not update the plot:

using Dash, DashHtmlComponents, DashCoreComponents, PlotlyBase

app = dash()

plt = Plot(scatter(; y = randn(10)))

function data_producer(pl)
    while true
        extendtraces!(pl, Dict(:y => [[randn()]]))
        sleep(1)
    end
end
task = @async data_producer(plt)

app.layout = html_div() do
    dcc_graph(id = "figure", figure = plt)
end

run_server(app, "127.0.0.1", 8050, debug = true)

Ref: https://discourse.julialang.org/t/update-plotlyjs-plot-in-dash-with-async-data/66298

mzaffalon avatar Aug 13 '21 08:08 mzaffalon

The missing element was generating the event with dcc_interval. Here is the complete example.

using Dash, DashHtmlComponents, DashCoreComponents, PlotlyBase

plt = Plot(scatter(; y = randn(10)))

function data_producer(pl)
    while true
        extendtraces!(pl, Dict(:y => [[randn()]]))
        sleep(1)
    end
end

# generate the data asynchronously
@async data_producer(plt)


app = dash()

app.layout = html_div() do
    dcc_graph(id="theplot", figure=plt),
    dcc_interval(id="plot-updater", interval=2000)
end

callback!(app,
          Output("theplot", "figure"),
          [Input("plot-updater", "n_intervals")]) do n
    plt
end

run_server(app, "127.0.0.1", 8050, debug=true)

I find the example useful: should I make a PR?

mzaffalon avatar Aug 27 '21 06:08 mzaffalon

That's great, good work!

@jackparmer do you think we can make use of that in the dash-julia docs?

sglyon avatar Aug 27 '21 12:08 sglyon

yeah, I believe that this would be the analogous chapter in Python - https://dash.plotly.com/live-updates

jackparmer avatar Aug 27 '21 23:08 jackparmer