Seaborn jointplot group colour coding (for both scatter and density plots)

我是研究僧i 提交于 2021-02-07 06:34:23

问题


I would like to use sns.jointplot to visualise the association between X and Y in the presence of two groups. However, in

tips = sns.load_dataset("tips")
sns.jointplot("total_bill", "tip", data=tips) 

there is no "hue" option as in other sns plots such as sns.scatterplot. How could one assign different colours for different groups (e.g. hue="smoker") in both the scatter plot, as well as the two overlapping density plots.

In R this could be done by creating a scatter plot with two marginal density plots as shown in here.

What is the equivalent in sns? If this is not possible in sns, is there another python package that can be used for this?


回答1:


jointplot is a simple wrapper around sns.JointGrid. If you create a JointGrid object and add plots to it manually, you will have much more control over the individual plots.

In this case, your desired jointplot is simply a scatterplot combined with a kdeplot, and what you want to do is pass hue='smoker' (for example) to scatterplot.

The kdeplot is more complex; seaborn doesn't really support one KDE for each class, AFAIK, so I was forced to plot them individually (you could use a for loop with more classes).

Accordingly, you can do this:

import seaborn as sns

tips = sns.load_dataset('tips')
grid = sns.JointGrid(x='total_bill', y='tip', data=tips)

g = grid.plot_joint(sns.scatterplot, hue='smoker', data=tips)
sns.kdeplot(tips.loc[tips['smoker']=='Yes', 'total_bill'], ax=g.ax_marg_x, legend=False)
sns.kdeplot(tips.loc[tips['smoker']=='No', 'total_bill'], ax=g.ax_marg_x, legend=False)
sns.kdeplot(tips.loc[tips['smoker']=='Yes', 'tip'], ax=g.ax_marg_y, vertical=True, legend=False)
sns.kdeplot(tips.loc[tips['smoker']=='No', 'tip'], ax=g.ax_marg_y, vertical=True, legend=False)



来源:https://stackoverflow.com/questions/55839345/seaborn-jointplot-group-colour-coding-for-both-scatter-and-density-plots

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!