python中的散点图,根据不同的分类变量制作颜色和形状

时间:2018-02-21 16:11:35

标签: python seaborn scatter

我需要生成散点图,其中多个分类变量可以通过散射的颜色和形状来表示。例如,

df = pd.DataFrame({'animals':pd.Series(['tiger','cheetah','lion','giraffe','elephant','gorilla']),
               'weight': pd.Series([200,120,240,240,400,300]),
               'meal': pd.Series([20,10,40,15,40,30]),
               'region': pd.Categorical(["Asian","American","African","African",'Asian','American']),
              'gender': pd.Categorical(["female","female","male","female",'male','male']),
              'group': pd.Series([True, False, False, True, True, True])})

sns.lmplot(data = df, x = 'weight', y = 'meal', hue = 'region', palette = 'Dark2',
       fit_reg = False, scatter_kws={"s": 20}, size = 4)

这将创建一个图,其中区域由不同的颜色表示。 但我还需要以不同的形式表现性别。因此颜色显示区域,形状显示性别。 有没有办法实现这个目标?谢谢你的任何建议!

enter image description here

1 个答案:

答案 0 :(得分:1)

您只需将通话中的标记列表传递给sns.lmplot

import seaborn as sns

df = pd.DataFrame({'animals':pd.Series(['tiger','cheetah','lion','giraffe','elephant','gorilla']),
               'weight': pd.Series([200,120,240,240,400,300]),
               'meal': pd.Series([20,10,40,15,40,30]),
               'region': pd.Categorical(["Asian","American","African","African",'Asian','American']),
              'gender': pd.Categorical(["female","female","male","female",'male','male']),
              'group': pd.Series([True, False, False, True, True, True])})

sns.lmplot(data = df, x = 'weight', y = 'meal', hue = 'region', palette = 'Dark2',
       fit_reg = False, scatter_kws={"s": 20}, size = 4, markers=["o","+","x"])

plt.show()

给出了:

enter image description here