我想使用seaborn catplot来指定特定观察的颜色。在一个虚构的例子中:
import seaborn as sns
import random as r
name_list=['pepe','Fabrice','jim','Michael']
country_list=['spain','France','uk','Uruguay']
favourite_color=['green','blue','red','white']
df=pd.DataFrame({'name':[r.choice(name_list) for n in range(100)],
'country':[r.choice(country_list) for n in range(100)],
'fav_color':[r.choice(favourite_color) for n in range(100)],
'score':np.random.rand(100),
})
sns.catplot(x='fav_color',
y='score',
col='country',
col_wrap=2,
data=df,
kind='swarm')我想用'pepe‘的名字给所有的观察结果上色(或者用另一种独特的方式标记,它可以是标记)。我怎么能这么做呢?其他颜色我不介意,如果它们都一样就更好了。

发布于 2018-11-18 12:44:07
您可以通过向数据帧添加一个布尔列并将其用作catplot()调用的hue参数来获得所需的结果。这样,您将获得具有两种颜色的结果(一种用于pepe观察,另一种用于其余颜色)。结果可以在这里看到:

此外,还应设置参数legend=False,否则侧面将显示is_pepe的图例。
代码如下:
df['is_pepe'] = df['name'] == 'pepe'
ax = sns.catplot(x='fav_color',
y='score',
col='country',
col_wrap=2,
data=df,
kind='swarm',
hue='is_pepe',
legend=False) 此外,您可以使用参数palette和顶层函数sns.color_palette()为两种观测(pepe和not-pepe)指定所需的两种颜色,如下所示:
ax = sns.catplot(x='fav_color',
y='score',
col='country',
col_wrap=2,
data=df,
kind='swarm',
hue='is_pepe',
legend=False,
palette=sns.color_palette(['green', 'blue']))获取以下结果:

https://stackoverflow.com/questions/51772467
复制相似问题