【问题标题】:Existing Seaborn jointplot add to scatter plot part only现有的 Seaborn 联合图仅添加到散点图部分
【发布时间】:2021-02-26 23:44:32
【问题描述】:

有没有办法创建 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

【问题讨论】:

    标签: python seaborn jointplot


    【解决方案1】:
    • 使用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);
    

    【讨论】:

      猜你喜欢
      • 2019-04-15
      • 2022-01-17
      • 2023-04-10
      • 1970-01-01
      • 2021-08-06
      • 1970-01-01
      • 2020-12-04
      • 2019-05-06
      • 2020-07-03
      相关资源
      最近更新 更多