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

Viewed 167

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'))
0 Answers
Related