Search code examples
plotlyplotly-dashplotly-python

Plotly adjust figure size to indicator inside of it


I am using a plotly go.Indicator to show certain values of my dataset. This is my code:

import dash_core_components as dcc
import plotly.graph_objects as go

value = dff.shape[0]
fig = go.Figure()
fig.add_trace(go.Indicator(
    mode="number",
    value=value,
    domain={'row': 0, 'column': 0},
    title='Total number of incidences'
)
fig.update_layout(
    paper_bgcolor ='lightgray',
    grid={
        'rows': 1,
        'columns': 1,
        'pattern': 'independent'
    }
)

dcc.Graph(
    id='indicator-incidences',
    figure=fig
)

And here image is how the figure represents. As you can see, it expands to the total width of the page and has a height larger than necessary.

How can I achieve that the figure adjust the size to the indicator it contains?


Solution

  • The plotly indicator itself actually also takes up about all available space if you let it. You can see that this is the case if you display the plot without the use of dash:

    fig = go.Figure(
        go.Indicator(
            mode="number+delta",
            value=400,
            number={"prefix": "$"},
            delta={"position": "top", "reference": 320},
            domain={"x": [0, 1], "y": [0, 1]},
        )
    )
    
    fig.update_layout(
        paper_bgcolor="lightgray",
    )
    
    fig.show()
    

    There are two different ways in which you could approach resizing the graph. Either you add width and height attributes on the Figure:

    fig = go.Figure(
        go.Indicator(
            mode="number+delta",
            value=400,
            number={"prefix": "$"},
            delta={"position": "top", "reference": 320},
            domain={"x": [0, 1], "y": [0, 1]},
        )
    )
    
    fig.update_layout(
        paper_bgcolor="lightgray",
        height=500,  # Added parameter
    )
    
    fig.show()
    

    Or you target the Graph element using css. For including css in dash application see the documentation here.