只有一条彩色线的 Seaborn 多线图

Seaborn multi line plot with only one line colored

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

这是我目前拥有的:

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

但这不会将线条更改为灰色。我在想,这样以后,我可以自己加上红色的美国线.....

您可以使用 palette 参数将线条的自定义颜色传递给 sns.lineplot,例如:

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

df = pd.DataFrame({'year': [2018, 2019, 2020, 2018, 2019, 2020, 2018, 2019, 2020, ], 
                   'pop': [325, 328, 332, 125, 127, 132, 36, 37, 38], 
                   'country': ['USA', 'USA', 'USA', 'Mexico', 'Mexico', 'Mexico',
                               'Canada', 'Canada', 'Canada']})

colors = ['red', 'grey', 'grey']
sns.lineplot(x='year', y='pop', data=df, hue='country', 
             palette=colors, legend=False)

plt.ylim(0, 350)
plt.xticks([2018, 2019, 2020]);

虽然有图例仍然有用,因此您可能还想考虑修改 alpha 值(下面元组中的最后一个值)以突出显示美国。

red = (1, 0, 0, 1)
green = (0, 0.5, 0, 0.2)
blue = (0, 0, 1, 0.2)
colors = [red, green, blue]

sns.lineplot(x='year', y='pop', data=df, hue='country', 
             palette=colors)

plt.ylim(0, 350)
plt.xticks([2018, 2019, 2020]);

你可以使用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()

输出:

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

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)

输出: