简体   繁体   中英

Adding percentage to plotly bar

I have this data, https://www.kaggle.com/ahsen1330/us-police-shootings and am using plotly bar to visualize the data this is my code.

trace1= go.Bar(x=df['race'].value_counts().index, y=df['race'].value_counts())

trace2= go.Bar(x = df['threat_level'].value_counts().index, y=df['threat_level'].value_counts())

trace3= go.Bar(x=df['flee'].value_counts().index, y=df['flee'].value_counts())

trace4= go.Bar(x=df['arms_category'].value_counts().index, y=df['arms_category'].value_counts(), )

trace5 = go.Bar(x=df['year'].value_counts().index, y=df['year'].value_counts())

fig = make_subplots(rows=3, cols=2, specs=[[{"type": "bar"},{"type": "bar"}],
                                           [{"type": "bar"},{"type": "bar"}],
                                          [{"type": "bar"},None]],
                   subplot_titles=('Race Distribution','Threat Level Count In US Shooting','Flee In US Shooting',
                                  'Arms Category Used In US Shooting','Which Year Most Shooting occured'))

fig.append_trace(trace1,1,1)
fig.append_trace(trace2,1,2)
fig.append_trace(trace3,2,1)
fig.append_trace(trace4,2,2)
fig.append_trace(trace5,3,1)

fig['layout'].update(title='US Police Shooting Univariate Analysis',
                    height=1100, width=900,)
fig.update_traces(marker_color=['papayawhip','peachpuff','peru','pink','plum','powderblue','purple'])

fig.show()

I want to add percentage at the top of graph but don't know how to do it. I have tried searching online for solution but can't seem to find solution for this. Really appreciate if someone can guide me.

Try to add:

fig = go.Bar(text='calc')

in your bar part.

eg here:

go.Bar(x=df['year'].value_counts().index, y=df['year'].value_counts())

Where 'calc' are the calculated percentages you have to add to your data set as columns as the police shooting data set has no % as columns. We do not know which percentages you want so you have to calculate them by yourself.

In addition add the position for the text outside of the bars:

fig.update_traces(textposition='outside')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM