首先,创建一个名为data_analysis的工程,并将数据文件score.csv放入该工程的根目录下。\n\n接下来,创建一个python文件,并导入csv和matplotlib.pyplot模块。\n\npython\nimport csv\nimport matplotlib.pyplot as plt\n\n\n然后,定义文件流,读取数据文件,并将文件数据加入一个列表中,并打印列表数据。\n\npython\ndata = []\nwith open('./score.csv', 'r') as file:\n reader = csv.reader(file)\n for row in reader:\n data.append(row)\nprint(data)\n\n\n接着,定义一个列表作为表头,内容为["编号", "姓名", "性别", "班级", "分数"]。\n\npython\nheader = ["编号", "姓名", "性别", "班级", "分数"]\n\n\n然后,定义6个变量用于存储每个班的总分与人数。\n\npython\ntotal_score_32101 = 0\ntotal_score_32102 = 0\ntotal_score_32103 = 0\nnum_students_32101 = 0\nnum_students_32102 = 0\nnum_students_32103 = 0\n\n\n接下来,通过列表数据计算每个班的平均分,并将计算结果存储到对应的变量中。\n\npython\nfor row in data[1:]:\n if row[3] == "大数据32101":\n total_score_32101 += int(row[4])\n num_students_32101 += 1\n elif row[3] == "大数据32102":\n total_score_32102 += int(row[4])\n num_students_32102 += 1\n elif row[3] == "大数据32103":\n total_score_32103 += int(row[4])\n num_students_32103 += 1\n\naverage_score_32101 = total_score_32101 / num_students_32101\naverage_score_32102 = total_score_32102 / num_students_32102\naverage_score_32103 = total_score_32103 / num_students_32103\n\n\n然后,绘制柱形图,横坐标为班级,纵坐标为平均成绩。\n\npython\nclasses = ["大数据32101", "大数据32102", "大数据32103"]\naverage_scores = [average_score_32101, average_score_32102, average_score_32103]\n\nplt.bar(classes, average_scores)\nplt.xlabel("班级")\nplt.ylabel("平均成绩")\nplt.title("各班级平均成绩")\nplt.show()\n\n\n最后,将数据插入柱形图并显示。\n\n请确保已安装所需的模块,并且在运行程序之前,将score.csv文件放入data_analysis工程的根目录下。

Python数据分析:使用matplotlib绘制各班级平均成绩柱形图

原文地址: https://www.cveoy.top/t/topic/ptzK 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录