现有的 Seaborn 关节图仅添加到散点图部分

时间:2021-02-26 23:44:32

标签: python seaborn jointplot

有没有办法创建一个 Seaborn Jointplot,然后将其他数据添加到散点图部分,而不是分布?

下面的示例在 df 上创建 df 和 Jointplot。然后我只想将 df2 添加到散点图上,并且仍然显示在图例中。

import pandas as pd
import seaborn as sns

d = {
    'x1': [3,2,5,1,1,0],
    'y1': [1,1,2,3,0,2],
    'cat': ['a','a','a','b','b','b']
}

df = pd.DataFrame(d)


g = sns.jointplot(data=df, x='x1', y='y1', hue='cat')

d = {
    'x2': [2,0,6,0,4,1],
    'y2': [-3,-2,0,2,3,4],
    'cat': ['c','c','c','c','d','d']
}
df2 = pd.DataFrame(d)
## how can I add df2 to the scatter part of g 
## but not to the distribution
## and still have "c" and "d" in my scatter plot legend

1 个答案:

答案 0 :(得分:2)

  • 使用 sns.scatterplot(..., ax=g.ax_joint) 将点添加到散点图,这将自动扩展图例以包括新的点类别。
  • 在生成联合图之前通过 selecting a color palette 分配新颜色,以便可以自动选择适当的新颜色。
import pandas as pd    # v 1.1.3
import seaborn as sns  # v 0.11.0

d = {
    'x1': [3,2,5,1,1,0],
    'y1': [1,1,2,3,0,2],
    'cat': ['a','a','a','b','b','b']
}

df = pd.DataFrame(d)

# Set seaborn color palette
sns.set_palette('bright')
g = sns.jointplot(data=df, x='x1', y='y1', hue='cat')

d = {
    'x2': [2,0,6,0,4,1],
    'y2': [-3,-2,0,2,3,4],
    'cat': ['c','c','c','c','d','d']
}
df2 = pd.DataFrame(d)

# Extract new colors from currently selected color palette
colors = sns.color_palette()[g.hue.nunique():][:df2['cat'].nunique()]

# Plot additional points from second dataframe in scatter plot of the joint plot
sns.scatterplot(data=df2, x='x2', y='y2', hue='cat', palette=colors, ax=g.ax_joint);

jointplot