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

如何编写Python函数绘制以年份为x轴的嵌套列表/数组多折线图

多折线图绘制问题修复方案

原代码存在的问题

  • 入参传递逻辑错误:将年份和分数数据打包为元组传入函数,遍历逻辑完全不符合「x轴为年份、单条折线对应单学科分数」的需求
  • 数据维度不匹配:要求折线对应二维数组的列,但直接遍历嵌套列表会按行读取,需要先转置数据结构
  • 图例配置错误:传入的字典格式无法直接被plt.legend识别,需要提取学科名作为标签
  • 绘图流程错误:plt.show()放在循环内部会导致每画一条线就弹出一个独立窗口,需要移到循环外部
  • 样式配置不合理:所有折线固定为红色,无法区分不同学科

修正后可运行代码

import matplotlib.pyplot as plt
import numpy as np

year = [2000,2001,2002,2003]
# 转成numpy数组方便后续按列遍历
notes = np.array([[10,11,11,14],[11,14,15,16],[15,14,12,11],[14,11,10,14]])
legend = {'maths':1, 'philosophy': 2, 'english': 3, 'biology': 4}
# 提取字典key作为图例标签
subjects = list(legend.keys())

def PlotData(x_year, y_notes, legend_labels):
    # 转置notes数组,按列遍历对应每个学科的历年分数
    for idx, subject_scores in enumerate(y_notes.T):
        plt.plot(x_year, subject_scores, marker = '.', 
                 markersize = 10, linestyle = 'solid', label=legend_labels[idx])
    plt.legend(loc ='upper left')
    plt.title('Final Examination')
    plt.xlabel('Year')
    plt.ylabel('Marks')
    # 所有折线绘制完成后再显示
    plt.show()

PlotData(year, notes, subjects)

内容的提问来源于stack exchange,提问作者Cressy de borbon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 19:24:04