Kevin
Kevin

Reputation: 299

Plot individual data points in each group after pandas groupby

I'd like to group a dataframe using several criteria and then visualize individual data points in each group using a scattered plot.

import pandas as pd
import seaborn as sns

df_tips = sns.load_dataset('tips')
df_tips.groupby(['sex', 'day', 'smoker'])['tip']    # How could I scatter plot individual tip in each group?

Ideally, I'd like to have something looks like this: enter image description here

Upvotes: 0

Views: 865

Answers (2)

Kevin
Kevin

Reputation: 299

I found a simpler way to do this and the plot is more beautiful (I think).

import pandas as pd
import seaborn as sns

df_tips = sns.load_dataset('tips')
df_tips['Groups'] = df_tips[['sex', 'day', 'smoker']].astype(str).agg('.'.join, axis=1)
sns.swarmplot(x='Groups', y='tip', data=df_tips)
plt.xticks(
    rotation=90, 
    fontweight='light',
    fontsize='x-large'  
)

Here is the output: enter image description here

Upvotes: 1

Quang Hoang
Quang Hoang

Reputation: 150735

I would do:

df_tips = sns.load_dataset('tips')
groups = df_tips.groupby(['sex', 'day', 'smoker'])['tip']

fig,ax = plt.subplots()
for  i,(k,v) in enumerate(groups):
    ax.scatter([i]*len(v), v)

ax.set_xticks(np.arange(len(groups)))
ax.set_xticklabels([k for k,v in groups],rotation=90);

Output:

enter image description here

Upvotes: 2

Related Questions