Pandas groupby scatter plot in a single plot

Question:

This is a followup question on this solution. There is automatic assignment of different colors when kind=line but for scatter plot that’s not the case.

import pandas as pd
import matplotlib.pylab as plt
import numpy as np

# random df
df = pd.DataFrame(np.random.randint(0,10,size=(25, 3)), columns=['label','x','y'])

# plot groupby results on the same canvas 
fig, ax = plt.subplots(figsize=(8,6))
df.groupby('label').plot(kind='scatter', x = "x", y = "y", ax=ax)

enter image description here

There is a connected issue here. Is there any simple workaround for this?

Update:

When I try the solution recommended by @ImportanceOfBeingErnest for a label column with strings, its not working!

df = pd.DataFrame(np.random.randint(0,10,size=(5, 2)), columns=['x','y'])
df['label'] = ['yes','no','yes','yes','no']
fig, ax = plt.subplots(figsize=(8,6))
ax.scatter(x='x', y='y', c='label', data=df) 

It throws following error,

ValueError: Invalid RGBA argument: ‘yes’

During handling of the above exception, another exception occurred:

Asked By: Venkatachalam

||

Answers:

You can use sns:

df = pd.DataFrame(np.random.randint(0,10,size=(100, 2)), columns=['x','y'])
df['label'] = np.random.choice(['yes','no','yes','yes','no'], 100)
fig, ax = plt.subplots(figsize=(8,6))
sns.scatterplot(x='x', y='y', hue='label', data=df) 
plt.show()

Output:

enter image description here

Another option is as what suggested in the comment: Map value to number, by categorical type:

fig, ax = plt.subplots(figsize=(8,6))
ax.scatter(df.x, df.y, c = pd.Categorical(df.label).codes, cmap='tab20b')
plt.show()

Output:

enter image description here

Answered By: Quang Hoang

Incase we have a grouped data already, then I find the following solution could be useful.

df = pd.DataFrame(np.random.randint(0,10,size=(5, 2)), columns=['x','y'])
df['label'] = ['yes','no','yes','yes','no']
fig, ax = plt.subplots(figsize=(7,3))


def plot_grouped_df(grouped_df,
                    ax,  x='x', y='y', cmap = plt.cm.autumn_r):

    colors = cmap(np.linspace(0.5, 1, len(grouped_df)))

    for i, (name,group) in enumerate(grouped_df):
        group.plot(ax=ax,
                   kind='scatter', 
                   x=x, y=y,
                   color=colors[i],
                   label = name)

# now we can use this function to plot the groupby data with categorical values
plot_grouped_df(df.groupby('label'),ax)

enter image description here

Answered By: Venkatachalam

You can loop over groupby and create a scatter per group. That is efficient for less than ~10 categories.

import pandas as pd
import matplotlib.pylab as plt
import numpy as np

# random df
df = pd.DataFrame(np.random.randint(0,10,size=(5, 2)), columns=['x','y'])
df['label'] = ['yes','no','yes','yes','no']

# plot groupby results on the same canvas 
fig, ax = plt.subplots(figsize=(8,6))

for n, grp in df.groupby('label'):
    ax.scatter(x = "x", y = "y", data=grp, label=n)
ax.legend(title="Label")

plt.show()

Alternatively you can create a single scatter like

import pandas as pd
import matplotlib.pylab as plt
import numpy as np

# random df
df = pd.DataFrame(np.random.randint(0,10,size=(5, 2)), columns=['x','y'])
df['label'] = ['yes','no','yes','yes','no']

# plot groupby results on the same canvas 
fig, ax = plt.subplots(figsize=(8,6))

u, df["label_num"] = np.unique(df["label"], return_inverse=True)

sc = ax.scatter(x = "x", y = "y", c = "label_num", data=df)
ax.legend(sc.legend_elements()[0], u, title="Label")

plt.show()

enter image description here

Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.