1

I am trying to plot a barplot from a grouped by 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:

 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: enter image description here

I would like to have similar barplot but using seaborn barplot function. I am unable to get it done. Can anyone please help?

2 Answers 2

1

You need to "melt" the dataframe to get a "long-form" dataframe.

df3 = df2.melt(id_vars=['year','month'])
sns.barplot(data=df3, x='month', y='value', hue='variable')

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

0

But finally this piece of code worked for me. Using melt to convert to long format was all I required.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.