如何在seaborn图形级图中指定调色板

Jay*_*umz 4 python palette seaborn facet-grid relplot

如果我需要进行特定的更改或面向细节的可视化,我已经学会了不要使用seaborn,但我觉得我有时没有充分利用它所提供的功能。

  • 我有一系列绘制簇成员资格的二维切片。
  • 问题在于案例之间,簇的数量存在变化,这导致seaborn在每个案例中重置调色板,导致不同的簇使用相同的颜色。

我想专门用seaborn 指定调色板。我不确定我是否遗漏了一些东西,或者这是使用facetgrid时无法解决的细节?

df = pd.DataFrame()
df['I'] = np.full(20,1)
df['J'] = np.arange(0,20,1)
df['K'] = [1]*12 + [2]*8
df['CM_Hard'] = [1]*10 + [2] + [0] + [2]*8 
df['Realization'] = ['p25']*10 + ['p50']*9 + ['p75']

for layer in df['K'].unique():
    layer_data_slice = df.groupby('K').get_group(layer)

    g = sns.FacetGrid(layer_data_slice, col="Realization",hue="CM_Hard")
    g.map_dataframe(sns.scatterplot, x="I", y="J", s=50, marker='+', palette='deep')
    g.add_legend()

    g.fig.suptitle("Training Realizations, Layer: {}".format(int(layer)), size=16, y=1.05)
    figure_title = 'Training_Layer_{}'.format(int(layer))
Run Code Online (Sandbox Code Playgroud)

链接到具有重复调色板的当前绘图问题

我尝试使用以下内容进行调色板定义,但它不会影响绘图:

palette = {0:"tab:cyan", 1:"tab:orange", 2:"tab:purple"}
Run Code Online (Sandbox Code Playgroud)

已尝试使用“tab:color”、“color”和 RGB 参考,但没有成功。没有错误,它只是在更改时不执行任何操作。

Tre*_*ney 6

  • 更新至seaborn 0.11.2。FacetGrid不建议直接使用。使用seaborn.relplotwithkind='scatter'绘制图形级图。
  • in必须keyspalette传递给 的列中的唯一值匹配hue
  • 测试于python 3.8.12, pandas 1.3.4, matplotlib 3.4.3,seaborn 0.11.2
import seaborn as sns

# load the data - this is a pandas.DataFrame
tips = sns.load_dataset('tips')

# set the hue palette as a dict for custom mapping
palette = {'Lunch': "tab:cyan", 'Dinner':"tab:purple"}

# plot
p = sns.relplot(kind='scatter', data=tips, col='smoker', x='total_bill', y='tip', hue='time', palette=palette)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 使用添加到 OP 的新样本数据
  • 如果该'K'列重命名为'Layer',则子图标题将与您的示例匹配:df = df.rename({'K': 'Layer'}, axis=1)
p = sns.relplot(data=df, x='I', y='J', s=50, marker='+', row='Layer', col='Realization', hue='CM_Hard', palette=palette, height=4)
p.fig.suptitle('Training Realizations', y=1.05, size=16)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

FacetGrid

  • 请注意,这palette是在FacetGrid通话中,而不是map_dataframe
for layer in df['K'].unique():
    layer_data_slice = df.groupby('K').get_group(layer)

    g = sns.FacetGrid(layer_data_slice, col="Realization",hue="CM_Hard", palette=palette)
    g.map_dataframe(sns.scatterplot, x="I", y="J", s=50, marker='+')
    g.add_legend()

    g.fig.suptitle("Training Realizations, Layer: {}".format(int(layer)), size=16, y=1.05)
    figure_title = 'Training_Layer_{}'.format(int(layer))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述