Python 从df绘制分组条形图
我很难用我的df的给定结构制作分组条形图,如下所示:Python 从df绘制分组条形图,python,pandas,plotly,bar-chart,Python,Pandas,Plotly,Bar Chart,我很难用我的df的给定结构制作分组条形图,如下所示: yhat yhat_upper yhat_lower cat grp cycle_label 0 5.716087e+08 6.123105e+08 5.319125e+08 yello costs funding1 1 1.501483e+08 1.641132e+08 1.452377e+08 blue costs funding1 2 7.217570e+
yhat yhat_upper yhat_lower cat grp cycle_label
0 5.716087e+08 6.123105e+08 5.319125e+08 yello costs funding1
1 1.501483e+08 1.641132e+08 1.452377e+08 blue costs funding1
2 7.217570e+08 7.764237e+08 6.771502e+08 Total costs funding1
3 3.066355e+08 3.473373e+08 2.669394e+08 yello costs funding2
4 5.277504e+07 6.673995e+07 4.786445e+07 blue costs funding2
5 3.594106e+08 4.140773e+08 3.148039e+08 Total costs funding2
我想要一个条形图,显示沿x轴按“循环标签”值分组的每个“cat”列。我已经试过了,但不起作用:
fig.add_trace(go.Bar(x=sum_matrix_tmp_df['cycle_label'], y=sum_matrix_tmp_df['yhat'],
name=sum_matrix_tmp_df['cat'])
任何帮助都将不胜感激 您可以执行
groupby
操作,然后执行求和
,例如:
df.groupby('cycle_label').sum().reset_index()
这将为您提供:
cycle_label yhat yhat_upper yhat_lower
0 funding1 1.443514e+09 1.552847e+09 1.354300e+09
1 funding2 7.188211e+08 8.281546e+08 6.296078e+08
要使用matplotlib进行基本打印,请执行以下操作:
plt.bar([0,1],df.groupby('cycle_label').sum().reset_index()['yhat'])
给你:
我相信在plotly中也可以做类似的事情。将数据框按要分组的列进行拆分,然后使用plotly创建基于它的图形
import plotly.graph_objects as go
f1 = tmp_df[tmp_df['cycle_label'] == 'funding1']
f2 = tmp_df[tmp_df['cycle_label'] == 'funding2']
cats = df['cat'].unique().tolist()
fig = go.Figure()
fig.add_trace(go.Bar(x=cats, y=f1['yhat'], name='funding1'))
fig.add_trace(go.Bar(x=cats, y=f2['yhat'], name='funding2'))
fig.show()
您的错误消息是什么?另一件事:您想按循环标签分组,然后您想打印什么?你的意思、总数等?太好了,谢谢。这就是我要找的。