【问题标题】:How to sync Colors across Subplots of different types Seaborne / Matplotlib如何在不同类型的 Seaborne / Matplotlib 子图中同步颜色
【发布时间】:2018-01-31 01:28:26
【问题描述】:

我正在尝试创建一个包含两个图的子图。第一个图本质上是散点图(我使用的是 regplot),第二个图是直方图。

我的代码如下:

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

data = {'source':['B1','B1','B1','C2','C2','C2'],
        'depth':[1,4,9,1,3,10],
        'value':[10,4,23,78,24,45]}

df = pd.DataFrame(data)

f, (ax1, ax2) = plt.subplots(1,2)

for source in df['source'].unique():

    x = df.loc[df['source'] == source, 'value']
    y = df.loc[df['source'] == source, 'depth']

    sns.regplot(x,
                y,
                scatter = True,
                fit_reg = False,
                label = source,
                ax = ax1)
    ax1.legend()

    sns.distplot(x,
                 bins = 'auto',
                 norm_hist =True,
                 kde = True,
                 rug = True,
                 ax = ax2,
                 label = source)
    ax2.legend()
    ax2.relim()
    ax2.autoscale_view()
plt.show()

结果如下所示。

如您所见,散点图和直方图之间的颜色不同。现在,我玩弄了彩色托盘和所有东西,但没有奏效。谁能解释我如何同步颜色?

谢谢。

【问题讨论】:

    标签: python pandas matplotlib colors seaborn


    【解决方案1】:

    使用color 绘图函数参数。在此示例中,您的 for 循环中的当前 seaborn 调色板与要绘制的 itertools.cyclecolors 被一一选择:

    import pandas as pd 
    import matplotlib.pyplot as plt 
    import seaborn as sns 
    import itertools
        
    data = {'source':['B1','B1','B1','C2','C2','C2'],
            'depth':[1,4,9,1,3,10],
            'value':[10,4,23,78,24,45]}
    
    df = pd.DataFrame(data)
    
    f, (ax1, ax2) = plt.subplots(1,2)
    
    # set palette 
    palette = itertools.cycle(sns.color_palette())
    
    # plotting 
    for source in df['source'].unique():
    
        x = df.loc[df['source'] == source, 'value']
        y = df.loc[df['source'] == source, 'depth']
    
        # color
        c = next(palette)
        sns.regplot(x,
                    y,
                    scatter = True,
                    fit_reg = False,
                    label = source,
                    ax = ax1,
                    color=c)
        ax1.legend()
    
        sns.distplot(x,
                     bins = 'auto',
                     norm_hist =True,
                     kde = True,
                     rug = True,
                     ax = ax2,
                     label = source,
                     color=c)
        ax2.legend()
        ax2.relim()
        ax2.autoscale_view()
    
    plt.show()
    

    您可以设置自己的color palette,例如this answer

    【讨论】:

    • 太完美了。非常感谢您的回答。
    【解决方案2】:

    我有一个非常相似的问题。

    这是 Serenity 答案的替代方案(突出显示原始代码的新部分):

    import pandas as pd
    import matplotlib.pyplot as plt
    import seaborn as sns
    
    data = {'source':['B1','B1','B1','C2','C2','C2'],
            'depth':[1,4,9,1,3,10],
            'value':[10,4,23,78,24,45]}
    
    df = pd.DataFrame(data)
    
    f, (ax1, ax2) = plt.subplots(1,2)
    
    palette = sns.color_palette()
    for color,source in zip(palette,df['source'].unique()):
    
          x = df.loc[df['source'] == source, 'value']
          y = df.loc[df['source'] == source, 'depth']
    
          sns.regplot(x,
                      y,
                      scatter = True,
                      fit_reg = False,
                      label = source,
                      ax = ax1,
    
                    color=color)
    
          ax1.legend()
    
          sns.distplot(x,
                       bins = 'auto',
                       norm_hist =True,
                       kde = True,
                       rug = True,
                       ax = ax2,
                       label = source,
    
                     color=color)
    
          ax2.legend()
          ax2.relim()
          ax2.autoscale_view()
    plt.show()
    

    基本上,通过sns.color_palette() 获取 matplotlib 使用的颜色列表。

    循环遍历zip()-ped 对(color, source) 的列表,其中colorsns.color_palette() 返回的列表中,并在调用sns.xxxplot() 时指定color 作为参数。

    【讨论】:

      【解决方案3】:

      利用 hue_order 参数。

      来自 seaborn 文档: seaborn.countplot(*, x=None, y=None, hue=None, data=None, order=None, hue_order=None, orient=None, color=None, palette=None, 饱和度=0.75,dodge=True,ax=None,**kwargs)

      order, hue_order: 字符串列表,可选 为了绘制分类级别,否则级别是从数据对象中推断出来的

      例如:

      hue_order = target_0['CODE_GENDER'].unique()

      plt.subplot(2,2,1) sns.countplot(x='INCOME_BRACKET', hue ='GENDER',data = df_0,hue_order=hue_order,调色板 = 'mako'); plt.title("非违约者:收入范围 b/w 性别 - 目标 0");

      plt.subplot(2,2,2) sns.countplot(x='INCOME_BRACKET', hue ='GENDER',data = df_1,hue_order=hue_order,调色板 = 'mako'); plt.title("违约者:>收入括号 b/w 性别 - 目标 1" );

      输出如下:

      Two subplots with synced colors

      我意识到这是一个老问题。但是,这很简单(不确定之前是否有此选项可用),我在其他任何答案中都找不到,而且由于某种原因这些也不起作用。因此,此答案适用于仍在为此苦苦挣扎的其他人。

      【讨论】:

        猜你喜欢
        • 2013-09-23
        • 1970-01-01
        • 2017-04-20
        • 2014-04-03
        • 1970-01-01
        • 2023-02-03
        • 1970-01-01
        • 2022-08-23
        相关资源
        最近更新 更多