简体   繁体   English

Plotly 分组条形图来自 pandas df

[英]Plotly grouped bar chart from pandas df

I am having trouble making a grouped bar chart with the given structure of my pandas df which looks like this:我无法使用 pandas 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+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

I want a bar chart that shows each "cat" column grouped by the "cycle_label" values along the x-axis.我想要一个条形图,显示按 x 轴上的“cycle_label”值分组的每个“cat”列。 I've tried this but not working:我试过这个但没有工作:

fig.add_trace(go.Bar(x=sum_matrix_tmp_df['cycle_label'], y=sum_matrix_tmp_df['yhat'],
                name=sum_matrix_tmp_df['cat'])

Any help would be much appreciated!任何帮助将非常感激!

Split the dataframe by the columns you want to group and use plotly to create a graph based on it.按您要分组的列拆分 dataframe 并使用 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()

在此处输入图像描述

You can do the groupby operation followed by a sum , for example:您可以执行groupby操作,然后执行sum ,例如:

df.groupby('cycle_label').sum().reset_index()

This will give you:这会给你:

  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

To do a basic plot, using matplotlib, do:做一个基本的 plot,使用 matplotlib,做:

plt.bar([0,1],df.groupby('cycle_label').sum().reset_index()['yhat'])

giving you:给你:

在此处输入图像描述

I believe something similar can be done in plotly.我相信在 plotly 中可以做类似的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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