JuliaPlots / PlotlyJS.jl

Julia library for plotting with plotly.js
Other
418 stars 77 forks source link

update plot in Dash with asynchronous data #412

Open mzaffalon opened 3 years ago

mzaffalon commented 3 years ago

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 commented 3 years ago

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?

sglyon commented 3 years ago

That's great, good work!

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

jackparmer commented 3 years ago

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