簡體   English   中英

將百分比添加到 plotly 欄

[英]Adding percentage to plotly bar

我有這些數據, https://www.kaggle.com/ahsen1330/us-police-shootings ,我正在使用 plotly 條來可視化數據,這是我的代碼。

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()

我想在圖表頂部添加百分比,但不知道該怎么做。 我曾嘗試在線搜索解決方案,但似乎無法找到解決方案。 如果有人可以指導我,我真的很感激。

嘗試添加:

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

在你的酒吧部分。

例如這里:

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

其中 'calc' 是您必須作為列添加到數據集的計算百分比,因為警察射擊數據集沒有 % 作為列。 我們不知道您想要哪個百分比,因此您必須自己計算。

此外,為欄外的文本添加 position:

fig.update_traces(textposition='outside')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM