python - 如何在 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
完整代码
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))
解决方案
您可以在 countplot 中使用调色板参数,而不是使用颜色参数。您可以将调色板定义为颜色列表(在 HEX 代码中)并传递它,或者可以直接给出一个列表。
sns.countplot(x = df['Dependent'], palette=['#432371',"#FAAE7B"]);