You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Seaborn实现单橙色折线+多不同灰度折线(适配多年份)

解决方案

要实现2022年折线为橙色、其余年份用不同灰度显示,同时适配任意年份数量的场景,可以按以下步骤修改代码:

  1. 分离目标年份与其他年份:先提取数据中所有唯一年份,把2022年单独区分出来,剩下的年份用灰度调色板分配颜色。
  2. 动态生成灰度调色板:利用Seaborn的灰度系调色板(比如binary),根据非2022年的年份数量自动生成对应数量的不同灰度值,避免手动设置颜色。
  3. 构建调色板字典:将灰度值分配给非2022年,再单独指定2022年为橙色。

完整代码如下:

import seaborn as sns
import matplotlib.pyplot as plt

# 提取所有唯一年份
unique_years = df.year.unique()
target_year = 2022

# 筛选出非2022年的年份
non_target_years = [year for year in unique_years if year != target_year]

# 根据非目标年份的数量生成对应长度的灰度调色板
gray_palette = sns.color_palette("binary", n_colors=len(non_target_years))

# 构建调色板字典:非目标年份分配灰度,目标年份设为橙色
palette = dict(zip(non_target_years, gray_palette))
palette[target_year] = 'orange'

# 绘图
sns.set(rc={'figure.figsize':(12, 8)})
ax = sns.lineplot(
    x='week',
    y='Deduplication Ratio',
    hue='year',
    ci=None,
    data=df,
    palette=palette
)

plt.show()

关键说明

  • 灰度调色板可选其他Seaborn内置的灰度系,比如gist_gray、gray_r(反向灰度,亮到暗),按需替换"binary"即可。
  • 代码会自动根据非2022年的年份数量生成对应数量的灰度色,不管数据里有多少个其他年份都能适配,无需手动调整颜色值。

内容的提问来源于stack exchange,提问作者Lucas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 03:10:29