Jack022
Jack022

Reputation: 1257

Real time/updating Plotly chart in Python/Flask app?

I built a Webapp with Flask (with a JS frontend) and now i would like to add charts to show my data.

I managed to embed a chart on it but it's static, is there a way to make it dynamic (for example with random values so that i can later add my own data to it)?

def index():

    rng = pd.date_range('1/1/2011', periods=7500, freq='H')
    ts = pd.Series(np.random.randn(len(rng)), index=rng)

    graphs = [

        dict(
            data=[
                dict(
                    x= arr,
                    y=[10, 20, 30],
                    type='scatter'
                ),
            ],
            layout=dict(
                title='first graph'
            )
        ) 

    ]

    # Add "ids" to each of the graphs to pass up to the client
    # for templating
    ids = ['graph-{}'.format(i) for i, _ in enumerate(graphs)]

    # Convert the figures to JSON
    # PlotlyJSONEncoder appropriately converts pandas, datetime, etc
    # objects to their JSON equivalents
    graphJSON = json.dumps(graphs, cls=plotly.utils.PlotlyJSONEncoder)

    return render_template('index.html',
                           ids=ids,
                           graphJSON=graphJSON)

Upvotes: 0

Views: 3067

Answers (1)

Sebastian Loehner
Sebastian Loehner

Reputation: 1322

HTTP is stateless by nature, so if you want dynamic, you will have to do that in the frontend.

Without knowing more about your Frontend I cannot give concrete examples, but hopefully this puts you on the right track:

  • Update the chart data in constant intervals through AJAX calls to the backend.
  • With that extended data update the chart through Plotly.extendtraces

Upvotes: 1

Related Questions