When I do a pie chart like the one below, when I create multiline labels (using <br>
) the shorter lines tend to get center-aligned with the bigger lines. How can I left-align them instead?
If possible, I would like the labels that are inside the pie chart to be center-aligned, and for the labels that are outside (the ones corresponding to the smallest slices) to be left-aligned. Is this possible? Hereβs the plot, and the code below:
threshold = 5
total = df.sum()
slice_percentages = (df / total) * 100
pull_values = [0.0 if p >= threshold else 0.2 for p in slice_percentages]
text_positions = ['inside' if p >= threshold else 'outside' for p in slice_percentages]
# Apply PSR_TYPE_MAPPING to the names
names = df.index.map(lambda x: PSR_TYPE_MAPPING.get(x, x))
# Create a DataFrame with our calculated percentages
plot_df = pd.DataFrame({
'names': names,
'values': df.values,
'percentages': slice_percentages
})
fig = px.pie(
plot_df,
values='values',
names='names',
title="Electricity Mix by Source Type (Averaged Power)",
color_discrete_sequence=px.colors.qualitative.Set3,
hole=.2,
custom_data=['percentages'] # Include our calculated percentages
)
fig.update_traces(
textinfo='percent+label',
textposition=text_positions,
pull=pull_values,
texttemplate='%{label}<br>%{value:.1f} MW | %{customdata[0]:.1f}%', # Use our calculated percentages
textfont=dict(size=10),
insidetextorientation='auto',
# insidetextanchor="start"
)
fig.update_layout(
showlegend=True,
width=1200,
height=900,
title_x=0.5,
legend=dict(
orientation="v",
yanchor="middle",
y=0.5,
xanchor="right",
x=1.9
),
annotations=[dict(
text="Source: Energy Data",
showarrow=False,
x=0.5,
y=-0.1,
xref="paper",
yref="paper"
)]
)