Search code examples
pythonpython-3.xplotlyplotly-dashdashboard

responsive charts with Plotly-Dash


How can I make charts responsive? So that by changing the size of the browser or on any device, the size of the charts fits the size of the browser page? Thank you for your help

fig1= px.line(a,x=m,y=t1)
fig2= px.bar(a,x=m,y=t2)
app =dash.Dash(__name__,title='me')
app.layout = html.Div(children=[
    html.Div(children=[
        dcc.Graph(figure=fig1 ),
        dcc.Graph(figure=fig2)
    ], style={'display':'flex'}
    )])

Solution

  • A key element here is the responsive parameter when creating the dcc.Graph objects. I let you check the detailed documentation, but basically:

    If True, the Plotly.js plot will be fully responsive to window resize and parent element resize event.

    Once you've set the responsivness to True you might want to play with the css flexbox attributes. IMO, the Code-Tricks Complete Guide to Flexbox is excellent to understand how it works.

    You might want the following style to take the whole width space, properly resize, and wrap when the figures reach a minimal size.

    graph_style = {"flex": 1, "min-width": 700}  # Set the min-width you want
    app.layout = html.Div(
        children=[
            html.Div(
                [
                    dcc.Graph(figure=fig1, responsive=True, style=graph_style),
                    dcc.Graph(figure=fig2, responsive=True, style=graph_style),
                ],
                style={"display": "flex", "flex-wrap": "wrap"},
            )
        ]
    )
    

    Here is a fully working example

    import plotly.express as px
    from dash import Dash, html, dcc
    
    df = px.data.gapminder().query("country == 'Canada'")
    
    fig_bar = px.bar(df, x="year", y="pop")
    fig_line = px.line(df, x="year", y="lifeExp", title="Life expectancy in Canada")
    
    app = Dash(__name__)
    
    graph_style = {"flex": 1, "min-width": 700}
    app.layout = html.Div(
        children=[
            html.Div(
                [
                    dcc.Graph(figure=fig_bar, responsive=True, style=graph_style),
                    dcc.Graph(figure=fig_line, responsive=True, style=graph_style),
                ],
                style={"display": "flex", "flex-wrap": "wrap"},
            )
        ]
    )
    
    
    if __name__ == "__main__":
        app.run_server(debug=True)