[英]Plotting grouped barplot using seaborn
I am trying to plot a barplot from a grouped by dataframe.我正在尝试 plot 来自按 dataframe 分组的条形图。
Here is my sample code:这是我的示例代码:
df2 = df.groupby(['month','year']).value.mean().unstack(0)
fig=plt.figure()
df2 = df2.reset_index()
ax= df2.plot(kind='bar',figsize=(15,6))
Here is my sample df2 output:这是我的示例 df2 output:
month year Apr Aug Dec Feb Jan Jul Jun Mar May Nov Oct Sep
0 2016 NaN 31049.193548 27832.419355 NaN NaN 24109.678571 21875.105263 NaN 19432.400000 40448.633333 27398.322581 41476.866667
1 2017 30878.733333 47712.451613 48420.580645 31113.071429 32785.161290 65806.838710 43577.500000 29369.096774 34244.290323 57701.566667 47438.709677 47376.800000
2 2018 62350.833333 62831.612903 80047.483871 65679.000000 58580.096774 63591.064516 70117.000000 62693.774194 56562.870968 78688.333333 113663.275862 65941.733333
3 2019 89368.433333 102717.310345 150733.500000 105968.357143 102056.516129 97236.566667 90435.642857 91214.483871 91439.903226 143166.428571 122802.272727 97268.833333
Here is my sample graph when I use dataframe plot function as in my code:这是我在代码中使用 dataframe plot function 时的示例图:
I would like to have similar barplot but using seaborn barplot function.我想要类似的条形图,但使用 seaborn 条形图 function。 I am unable to get it done.
我无法完成它。 Can anyone please help?
有人可以帮忙吗?
But finally this piece of code worked for me.但最后这段代码对我有用。 Using melt to convert to long format was all I required.
我只需要使用 melt 转换为长格式。
df2 = df.groupby(['year','month']).value.mean()
df2 = df2.reset_index(inplace=False, drop=False)
df2 = df2.dropna()
df3 = df2.melt(id_vars=['year','month'])
df3
sns.barplot(data=df3, x='year', y='value', hue='month')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.