Seaborn 多线图,仅一根线着色

TYL*_*TYL 2 python linechart matplotlib seaborn

我正在尝试使用 sns 绘制多线图,但仅将美国线保持为红色,而其他国家/地区为灰色

这是我到目前为止所拥有的:

df = px.data.gapminder()
sns.lineplot(x = 'year', y = 'pop', data = df, hue = 'country', color = 'grey', dashes = False, legend = False)
Run Code Online (Sandbox Code Playgroud)

但这不会将线条更改为灰色。我想在这之后,我可以单独添加红色的美国线......

Qua*_*ang 7

您可以使用 pandas groupby 来绘制:

fig,ax=plt.subplots()
for c,d in df.groupby('country'):
    color = 'red' if c=='US' else 'grey'
    d.plot(x='year',y='pop', ax=ax, color=color)

ax.legend().remove()
Run Code Online (Sandbox Code Playgroud)

输出:

在此输入图像描述

要保留默认调色板的原始颜色,但将其余颜色灰显,您可以选择color='grey'仅在满足条件时才通过:

fig,ax=plt.subplots()
for c,d in df.groupby('country'):
    color = 'red' if c=='US' else 'grey'
    d.plot(x='year',y='pop', ax=ax, color=color)

ax.legend().remove()
Run Code Online (Sandbox Code Playgroud)

或者您可以将特定调色板定义为字典:

palette = {c:'red' if c=='US' else 'grey' for c in df.country.unique()}

sns.lineplot(x='year', y='pop', data=df, hue='country', 
             palette=palette, legend=False)
Run Code Online (Sandbox Code Playgroud)

输出:

在此输入图像描述