I want to have the percentage values shown ontop of the pie wedge and have the labels next to the wedge. In Matplot this is pretty easy
I can’t get the same thing in plotly though, despite my efforts, any suggestions?
import plotly.graph_objects as go
import numpy as np
Sample data
labels = [‘Apple’, ‘Banana’, ‘Cherry’, ‘Date’]
values = np.array([4500, 2500, 1050, 1500]) # Convert values to a NumPy array
Create the pie chart
fig = go.Figure(data=[go.Pie(labels=labels, values=values, textinfo=‘label’, insidetextorientation=‘horizontal’)])
Customize the trace for displaying labels outside
fig.update_traces(
textposition=‘outside’, # Display labels outside the pie
marker=dict(line=dict(color=‘#000000’, width=2)),
hoverinfo=‘label+percent’
)
Calculate midpoints for each slice for proper percentage placement
angle_sum = np.cumsum(values) - values / 2
total_sum = sum(values)
mid_angles = angle_sum / total_sum * 2 * np.pi # convert to radians
Add annotations for percentages directly on the slices
for angle, value in zip(mid_angles, values):
x = 0.5 + 0.5 * np.cos(angle) # X position
y = 0.5 + 0.5 * np.sin(angle) # Y position
percentage = f"{(value / total_sum * 100):.1f}%"
fig.add_annotation(
x=x, y=y,
xref="paper", yref="paper",
text=percentage, # The percentage value
showarrow=False,
font=dict(size=12, color="white"), # Ensure text is visible on slices
align='center'
)
Update layout to ensure everything fits
fig.update_layout(
title_text=‘Fruit Consumption’,
showlegend=False # Disable the legend
)
Show the figure
fig.show()