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

如何用Pandas和Seaborn绘制多时间序列并自定义样式与图例

院校分数序列与年度均值同图绘制及图例自定义解决方案

数据结构

我有一份整理好的院校分数DataFrame,结构如下:

uni                             score   year
18  Arden University Limited        78.95   2020
245 The University of Manchester    71.35   2022
113 Darlington College              93.33   2020
94  City of Wolverhampton College   92      2017
345 The Royal Veterinary College    94      2018
118 Darlington College              62      2018

已实现代码

已完成单个院校时间序列绘图函数:

# 创建绘图函数
def plot_uni(df, uni, query):
    print(query)
    df['query'] = df[uni].str.contains(query)
    subset = df[df['query']].set_index("year")
    subset.sort_index().plot()

同时可绘制年度整体均值折线图:

df.groupby("year").mean()['score'].plot()

需求

需将单个/多个院校分数序列与整体均值序列绘制在同一张图中,支持自定义颜色规则:

  • 整体均值为红色
  • 指定重点院校为蓝色
  • 其余院校为灰色
    目前已完成绘图,但无法正确修改图例。

解决方案

1. 重构绘图函数,支持多院校与自定义颜色

重构函数,先计算年度均值,再逐个绘制院校序列,最后统一控制图例:

import matplotlib.pyplot as plt

def plot_uni_with_mean(df, target_unis, highlight_color='blue', mean_color='red', other_color='gray'):
    # 计算并绘制年度整体均值
    yearly_mean = df.groupby("year").mean()['score'].sort_index()
    mean_line, = plt.plot(yearly_mean.index, yearly_mean.values, color=mean_color, label='年度整体均值')
    
    # 存储线条对象与对应标签,用于自定义图例
    lines = [mean_line]
    labels = ['年度整体均值']
    
    # 遍历目标院校,逐个绘制
    for uni in target_unis:
        uni_data = df[df['uni'] == uni].sort_values('year')
        # 为重点院校设置高亮色,其余用灰色(这里默认第一个院校为重点,可按需调整规则)
        color = highlight_color if uni == target_unis[0] else other_color
        uni_line, = plt.plot(uni_data['year'], uni_data['score'], color=color, label=uni)
        lines.append(uni_line)
        labels.append(uni)
    
    # 自定义图例
    plt.legend(lines, labels, loc='upper right')  # 可通过loc参数调整图例位置
    plt.xlabel('年份')
    plt.ylabel('分数')
    plt.title('院校分数与年度均值对比')
    plt.show()

2. 调用示例

对比重点院校Darlington College(蓝色)、普通院校The University of Manchester(灰色)与年度均值(红色):

target_unis = ['Darlington College', 'The University of Manchester']
plot_uni_with_mean(df, target_unis)

3. 图例修改关键说明

  • 通过plt.legend()直接传入预先定义的lines(线条对象列表)和labels(标签列表),完全自定义图例内容与顺序
  • 若需调整图例样式,可添加参数,比如fontsize=10设置字体大小,frameon=False去掉边框
  • 重点院校的判断规则可灵活修改,比如传入单独的highlight_unis列表来指定哪些院校用高亮色

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 21:05:20