在seaborn catplot中指定颜色 [英] specify color in seaborn catplot

查看:108
本文介绍了在seaborn catplot中指定颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 seaborn catplot 指定特定观察的颜色.在一个虚构的例子中:

I would like to specify the color of particular observations using seaborn catplot. In a made up exemple:

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".我该怎么做?我不介意其他颜色,如果它们都一样会更好.

I would like to colour (or mark in another distinctive way, it could be the marker) all the observations with the name 'pepe'. How I could do that ? The other colors I dont mind, it would be better if they are all the same.

推荐答案

您可以通过向数据框添加布尔列并将其用作 hue 参数来实现您想要的结果>catplot() 调用.这样,您将获得两种颜色的结果(一种用于 pepe 观察,另一种用于其他观察).结果可以在这里看到:

You can achieve the results you want by adding a boolean column to the dataframe and using it as the hue parameter of the catplot() call. This way you will obtain the results with two colours (one for pepe observations and one for the rest). Results can be seen here:

此外,应设置参数 legend = False ,因为否则会在侧面显示 is_pepe 的图例.

Also, the parameter legend=False should be set since otherwise the legend for is_pepe will appear on the side.

代码如下:

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)指定您想要的两种颜色) 如下图:

Furthermore, you can specify the two colours you want for the two kinds of observations (pepe and not-pepe) using the parameter palette and the top-level function sns.color_palette() as shown below:

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']))

获得此结果:

这篇关于在seaborn catplot中指定颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆