gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 21:35:26 25 4
gpt4 key购买 nike

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

这是我目前所拥有的:

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

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

最佳答案

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

输出:

enter image description here

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

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)

输出:

enter image description here

关于python - 只有一条彩色线的 Seaborn 多线图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62020588/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com