Plotly: How to display the total sum of the values at top of a stacked bar chart along with the individual bar values?

Viewed 620

I am trying to add the total at the top of the each stacked bar along with the individual bar values in Plotly Express in Python.

import plotly.express as px
df = px.data.medals_long()
fig = px.bar(df, x="medal", y="count", color="nation", text_auto=True)
fig.show()

This gives the below result enter image description here

However I want the chart as below:

enter image description here

1 Answers

Although it can be annotated as a string, the easiest way is to add a graph in the text mode of a scatter plot.

import plotly.express as px
import plotly.graph_objects as go

df = px.data.medals_long()
dfs = df.groupby('medal').sum()
fig = px.bar(df, x="medal", y="count", color="nation", text_auto=True)

fig.add_trace(go.Scatter(
    x=dfs.index, 
    y=dfs['count'],
    text=dfs['count'],
    mode='text',
    textposition='top center',
    textfont=dict(
        size=18,
    ),
    showlegend=False
))

fig.update_yaxes(range=[0,50])
fig.show()

enter image description here

Related