How to can make a scatter plot of xy column but based on the value of 'id' column

Viewed 306

I have a dataframe like this.

 ID        X     Y CLASS  
  A      123   456     0 
  A      789   121     1 
  A      456   333     1
  B      111   123     1   
  B      156   123     1
  C      167   189     1
  C      567   789     1

I want to group the same values for 'id' and make different scatter plots based on the xy axis in the same figure. Right now, I am using

groups = df.groupby('id')

This makes separate groups and manually plotting for different id's but I'd like to do plot all the scatters in a single image and separate them based on the class. Sorry if the question is too 'noob'. Thanks for your time.

2 Answers

The following will give you different scatterplots for different IDs in the same image. I think this is what you want:

import matplotlib.pyplot as plt
import seaborn as sns
g=sns.FacetGrid(df, row='ID')
g=g.map(plt.scatter, x='Y', y='Y')
plt.show()

Alternatively, you can have one scatterplot with different point-colors for each ID with the following code:

import matplotlib.pyplot as plt
import seaborn as sns

sns.scatterplot(df['X'], df['Y'], hue = df['ID'])
plt.show()

To do it in the same plot, you can use:

import pandas as pd
import matplotlib.pyplot as plt

for name, group in df.groupby('ID'):
    plt.scatter(group.X, group.Y, label=name)
plt.legend()
plt.show()
Related