如何在seaborn中的计数图上设置自定义颜色

ale*_*ter 0 python colors matplotlib pandas seaborn

我创建了一组遵循特定配色方案的雨云图分布(来自seaborn的Set2)。我想让我的计数图与列出的组的颜色相匹配(例如:饮食组的男性和女性计数为绿色,mod-pa 的 m:f 计数为粉红色等)。但是我无法将调色板与 x 变量和色调对齐。看来 countplot 只会根据色调着色。

雨云图的配色方案 条形图的配色方案

我尝试过使用 set_colors 来操作哪些栏来改变颜色,我也尝试过根据如下条件映射颜色,但似乎没有任何效果。

ax = sns.countplot(x="Group", hue="Sex", data=df)
ax[0].set_color('r')

TypeError: 'AxesSubplot' object does not support indexing


value=(df['Group']=='DIET') & (df['Sex']=='Female')

df['color']= np.where( value==True , "#9b59b6", "#3498db")

ax = sns.countplot(x="Group", hue="Sex", data=df, color=df['color'])

TypeError: 'Series' objects are mutable, thus they cannot be hashed
Run Code Online (Sandbox Code Playgroud)

完整代码

import pandas as pd

import numpy as np

import seaborn as sns

df = pd.DataFrame({"Sex" : np.random.choice(["Male",  "Female"], size=1310, p=[.65, .35]),
                   "Group" : np.random.choice(["DIET", "MOD-PA", "HIGH-PA"],size=1310)})

# Unique category labels: 'Diet', 'MOD-PA'...
color_labels = df['Group'].unique()

# List of color palette to use
rgb_values = sns.color_palette("Set2", 6)

# Map label to color palette

color_map = dict(zip(color_labels, rgb_values))

ax = sns.countplot(x="Group", hue="Sex", data=df, palette=df['Group'].map(color_map))
Run Code Online (Sandbox Code Playgroud)

即使我映射到 x 变量(组),它仍然映射到色调变量(性别)

小智 12

您可以在 countplot 中使用调色板参数,而不是使用颜色参数。您可以将调色板定义为颜色列表(以十六进制代码表示)并传递它,或者可以直接给出一个列表。

    sns.countplot(x = df['Dependent'], palette=['#432371',"#FAAE7B"]);
Run Code Online (Sandbox Code Playgroud)