问题描述
我想使用 sns.jointplot 来可视化存在两个组的情况下 X 和 Y 之间的关联.然而,在
tips = sns.load_dataset("tips")sns.jointplot("total_bill", "tip", data=tips)
没有像 sns.scatterplot 等其他 sns 图中的色调"选项.如何在散点图中以及两个重叠的密度图中为不同的组(例如,hue="smoker")分配不同的颜色.
在 R 中,这可以通过创建具有两个边际密度图的散点图来完成,如
sns 中的等价物是什么?如果这在 sns 中是不可能的,是否有另一个可以用于此的 python 包?
jointplot
是对 sns.JointGrid
的简单包装.如果您创建一个 JointGrid
对象并手动向其中添加绘图,您将对单个绘图有更多的控制.
在这种情况下,你想要的jointplot
只是一个scatterplot
结合一个kdeplot
,你想要做的是传递hue='smoker'
(例如)到 scatterplot
.
kdeplot
更复杂;seaborn
并不真正支持每个类使用一个 KDE,AFAIK,所以我不得不单独绘制它们(你可以使用 for
循环和更多类).>
因此,您可以这样做:
导入 seaborn 为 sns提示 = sns.load_dataset('提示')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)
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
What is the equivalent in sns? If this is not possible in sns, is there another python package that can be used for this?
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)
这篇关于Seaborn 联合图组颜色编码(用于散点图和密度图)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!