我有这个数据,https://www.kaggle.com/ahsen1330/us-police-shootings 并且正在使用 plotly bar 来可视化数据,这是我的代码。
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()
我想在图表顶部添加百分比,但不知道该怎么做。我曾尝试在线搜索解决方案,但似乎无法找到解决方案。 如果有人可以指导我,真的很感激。
答案 0 :(得分:0)
尝试添加:
fig = go.Bar(text='calc')
在你的酒吧部分。
例如这里:
go.Bar(x=df['year'].value_counts().index, y=df['year'].value_counts())
其中 'calc' 是您必须作为列添加到数据集中的计算百分比,因为警察射击数据集没有 % 作为列。我们不知道您想要的百分比,因此您必须自己计算。
另外添加条形之外的文本位置:
fig.update_traces(textposition='outside')