Plotly offline with flask

后端 未结 2 1741
误落风尘
误落风尘 2021-02-03 14:25

How can I use plotly offline with flask . I know that plotly can be used offline with Ipython notebook , Can I use Plotly offline with flask ? If not , can someone please sugges

相关标签:
2条回答
  • 2021-02-03 14:45

    Edit: Updated for current Plotly version

    What you want to do is make functions that return the offline "plot" result as a html <div>. To do this, you call the offline.plot() method with the output_type="div" argument. This will return a pure string that you can then put in any flask template, and it will show the graph!

    Also, make sure to include the plotly.js library in your static files and link to them in your html pages that show graphs.

    This is an example of what I'm saying:

    import plotly.graph_object as go
    from plotly import io
    
    fig = go.Figure(data=barChart, layout=barLayout)
    
    div = io.to_html.plot(fig, show_link=False, output_type="div", include_plotlyjs=False)
    
    return div
    
    0 讨论(0)
  • 2021-02-03 15:04

    Update

    @DarenThomas In my usage, I simply import flask and create routes as usual.

    import flask
    
    # ... normal Dash stuff here
    
    @app.server.route('/error.csv')
    def serve_error():
        return flask.send_file('error.csv')
    

    =====================================================================

    For those looking in the future, this answer can be updated to include the Plotly side-project Dash. It comes out of the box with plotly/flask support and was extremely easy to get existing plotly graphs to show up in a web interface. For example:

    import dash
    import dash_core_components as dcc
    import dash_html_components as html
    
    app = dash.Dash()
    
    app.layout = html.Div(children=[
        html.H1(children='Hello Dash'),
    
        html.Div(children='''
            Dash: A web application framework for Python.
        '''),
    
        dcc.Graph(
            id='example-graph',
            figure={
                'data': [
                    {'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': 'SF'},
                    {'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': u'Montréal'},
                ],
                'layout': {
                    'title': 'Dash Data Visualization'
                }
            }
        )
    ])
    
    if __name__ == '__main__':
        app.run_server(debug=True)
    

    See also their tutorial series.

    0 讨论(0)
提交回复
热议问题