How to make 3D scatter plot with a hue?

Viewed 3375

I have four columns: sex, weight, height,age. I need to build with matplotlib or seaborn a 3dscatter plot, where x-axis=weight,y=height,z=age, and mark sex with dfferent colors. I was able only to build 2d scatter plot like this

sns.scatterplot(x = 'height', y = 'age',hue='sex',data=df, palette=['blue',"pink"])

but can't figure out how to add z-axis

1 Answers

You need to use matplotlib for this, I don't think there is an option for 3d scatter in seaborn:

import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np
import pandas as pd

df = pd.DataFrame({'height':np.random.uniform(160,190,20),
                   'weight':np.random.uniform(60,80,20),
                   'age':np.random.randint(20,60,20),
                   'sex':np.random.choice(['M','F'],20)
                  })

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

for s in df.sex.unique():
    ax.scatter(df.height[df.sex==s],df.weight[df.sex==s],df.age[df.sex==s],label=s)
    
ax.legend()

enter image description here

Related