【问题标题】:specify color in seaborn catplot在 seaborn catplot 中指定颜色
【发布时间】:2018-08-09 17:03:06
【问题描述】:

我想使用 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”的观察结果着色(或以另一种独特的方式进行标记,它可能是标记)。我怎么能那样做?其他颜色我不介意,如果都一样就更好了。

【问题讨论】:

  • Seaborn 在这里缺乏一点灵活性。所以我猜你不能用catplot 做到这一点。但是,使用 FacetGrid 并将自定义的 swarmplots 映射到它可能会起作用。 IE。使用一个函数,每个图绘制两个 swarmplot,一个包含所有数据,另一个包含“pepe”数据。

标签: python-3.x matplotlib seaborn


【解决方案1】:

您可以通过向数据框添加布尔列并将其用作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']))

获得此结果:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-16
    • 2016-01-04
    • 2017-11-04
    • 1970-01-01
    • 2023-01-17
    • 2021-07-28
    • 1970-01-01
    • 2019-11-10
    相关资源
    最近更新 更多