nishant
nishant

Reputation: 41

Grouping Bar Plot in seaborn

I am trying to plot BAR PLOT of two continuous variables side-by-side. Haven't been successful.

df_cooking= df.groupby(df['region'])['cook_time','prep_time'].mean().reset_index()
df_cooking.head(6)

    region      cook_time   prep_time
0   Central     48.333333   13.333333
1   East        41.607143   43.518519
2   North       41.979167   38.020833
3   North East  28.461538   28.846154
4   South       36.909091   58.181818
5   West        41.880597   16.924242

This is how I have tried it using seaborn:

plt.figure(figsize=(8,9))
plt.bar(df_cooking['region'],df_cooking['prep_time'], label = 'Preparation Time', color= 'c')
plt.bar(df_cooking['region'],df_cooking['cook_time'], label = 'Cooking Time', color = 'r')

plt.xlabel('Region')
plt.ylabel('Time in Minutes')
plt.title('Cooking and Preparation Time per Region')
plt.legend()
plt.show()

enter image description here

Thanks for help in advance!

Upvotes: 1

Views: 61

Answers (2)

StupidWolf
StupidWolf

Reputation: 46898

To use seaborn, you need to pivot the dataframe you have into a long format:

df = pd.DataFrame({'region':np.random.choice(['Central','East','West'],100),
                   'cook_time':np.random.uniform(0,1,100),
                   'prep_time':np.random.uniform(0,1,100)})

df_cooking= df[['cook_time','prep_time']].groupby(df['region']).mean().reset_index()

df_cooking.melt(id_vars='region')

region  variable    value
0   Central cook_time   0.516703
1   East    cook_time   0.519351
2   West    cook_time   0.486752
3   Central prep_time   0.463249
4   East    prep_time   0.539191
5   West    prep_time   0.520700

sns.barplot(data=df_cooking.melt(id_vars='region'),x='region',y='value',hue='variable')

enter image description here

Upvotes: 1

Quang Hoang
Quang Hoang

Reputation: 150735

There's no seaborn in your code. That said, you can, for example use:

df_cooking.plot.bar(x='region', y=['cook_time','prep_time'])

Upvotes: 0

Related Questions