Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep relative position of annotations constant in relation to Donut Charts using Plotly (Python)

How do I keep the position of annotations constant relative to the position of the donut charts as screen resolution changes? In my situation the title centered within the donut hole in some cases and centered above the chart in others. I see that this an issue in the examples given by Plotly for the Pie Charts in subplots: https://plotly.com/python/pie-charts/#pie-charts-in-subplots

I am aware that this is almost certainly because I am using constants for my x and y coordinates but I don't know how to make them relative.

Roughly correct positioning: Positions looking pretty good

Incorrect positioning after resizing window:

Positions looking less good

import plotly.graph_objects as go
from plotly.subplots import make_subplots

lst_abc = [153, 256]
lst_def = [1569, 724]
lst_ghi = [75618, 28971]
lst_long = [2, 5]

# Create subplots, using 'domain' type for pie charts
specs = [[{'type':'domain'}, {'type':'domain'}],
         [{'type':'domain'}, {'type':'domain'}]]

fig = make_subplots(rows=2, cols=2, specs = specs)

# Define pie charts                    
fig.add_trace(go.Pie(labels=[1,2], values=lst_abc, name='ABC'), 1, 1)
fig.add_trace(go.Pie(labels=[1,2], values=lst_def, name='DEF'), 1, 2)
fig.add_trace(go.Pie(labels=[1,2], values=lst_ghi, name='GHI'), 2, 1)
fig.add_trace(go.Pie(labels=[1,2], values=lst_long, name='Longer Title Here'),
              2, 2)

fig.update_traces(hole=.4, hoverinfo='percent', textinfo='value')

fig.update_layout(
    showlegend=False,
    # Add annotations in the center of the donut pies.
    annotations=[dict(text='ABC', x=0.213, y=0.805, font_size=15, showarrow=False),
                 dict(text='DEF', x=0.787, y=0.805, font_size=15, showarrow=False),
                 dict(text='GHI', x=0.213, y=0.200, font_size=15, showarrow=False),
                 dict(text='Longer Title Here', x=0.82, y=0.46, font_size=15,
                      showarrow=False)])
fig.show()

with open('Current Stats.html', 'a') as f:
        f.write(fig.to_html(full_html=False, include_plotlyjs='cdn'))
like image 925
John Anderson Avatar asked Jan 23 '26 08:01

John Anderson


1 Answers

I had the same issue, and I finally found a very easy solution ! You just have to use the title argument in the go.Pie() function, instead of name, and don't add any annotations in your update_layout() method

like image 149
Quentin GUIGNARD Avatar answered Jan 24 '26 22:01

Quentin GUIGNARD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!