0
votes

Shown below is the syntax used to get the bar chart for a categorical data on plotly express

df1= df['Catergory'].value_counts().reset_index(name='Total')

df1['Percentage'] = round((df1['Total'] / df1['Total'].sum())* 100,0)

fig = px.bar(df1, 
              x='index',
              y='values', 
              text_auto= False,
              text=df['Percentage'].apply(lambda x: '{0:1.1f}%'.format(x)))
fig.update_traces(textfont_size=12, textangle=0, cliponaxis=False, textposition="outside")
fig.show()

and the diagram looks like this

enter image description here

If " text_auto = True ", I would only get the value count instead of the percentage value.

How can I add both the value count along and the percentage value on the bar chart in plotly express like shown below

enter image description here

1

1 Answers

1
votes

At the annotation, it is possible to handle values and percentages at the same time.

import plotly.express as px
import pandas as pd

df1 = pd.DataFrame({'Category':['A','B','C','D'], 'Total':[150,200,30,40]})
df1['Percentage'] = round((df1['Total'] / df1['Total'].sum())*100,0)

fig = px.bar(df1, 
              x='Category',
              y='Total', 
              text_auto= False,
              text=['{}, {:.0%}'.format(v, p/100) for v,p in zip(df1['Total'], df1['Percentage'])]
            )
fig.update_traces(textfont_size=12, textangle=0, cliponaxis=False, textposition="outside")
fig.show()

enter image description here