如何在不同类型的子图上同步颜色Seaborne / Matplotlib

Bil*_*ler 6 python colors matplotlib pandas seaborn

我试图用两个图创建一个子图。第一个图实质上是散点图(我正在使用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()
Run Code Online (Sandbox Code Playgroud)

结果如下所示。

在此处输入图片说明

如您所见,散点图和直方图之间的颜色是不同的。现在,我在玩各种颜色的托盘,但都没有用。谁能阐明我如何同步颜色?

谢谢。

Ser*_*ity 5

使用color绘图函数的参数。在这个例子中,你的 for 循环中当前的 seaborn 调色板与itertools.cycle要绘制的颜色是一一选择的:

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()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

您可以像在这个答案中一样设置自己的调色板