我想用sns绘制一个多线图,但只把美国的线用红色表示,而其他国家的线用灰色表示。
这是我目前所掌握的情况。
df = px.data.gapminder()
sns.lineplot(x = 'year', y = 'pop', data = df, hue = 'country', color = 'grey', dashes = False, legend = False)
但这并没有把线条变成灰色。我在想,在这之后,我可以把美国的线单独添加为红色......我想用sns绘制多线图,但是只把美国的线变成红色,而其他国家的线变成灰色。
你可以使用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)
输出:
你可以使用 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]);
不过,有一个图例还是很有用的,所以你可能还想考虑调整一下阿尔法值(以下元组中的最后值),以突出美国。
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]);