读Excel数据,画条形图

本文详细介绍了如何从Excel文件中读取数据,处理并分析成绩预测的误差,使用Python的matplotlib库绘制条形图,直观展示不同成绩区间内的平均预测误差。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

画图部分转自https://blog.youkuaiyun.com/zhangxiaojiakele/article/details/78014627


目录

1. 处理数据

2. 画条形图

 导入包

from matplotlib import pyplot as plt
import numpy as np
from matplotlib.font_manager import FontProperties
import pandas as pd
font = FontProperties(fname=r"C:\Windows\Fonts\simhei.ttf", size=10.5)

处理数据

dataFile = 'error.xlsx'
trainData = pd.read_excel(dataFile)

inputData = np.array(trainData)
# print(inputData)
n = inputData.shape[0]
cols = inputData.shape[1]
d={'1':[0,0],'2':[0,0], '3':[0,0],'4': [0,0]}

for i in range(n):
    for j in range(cols):
        inputData[i][j] = np.float32(inputData[i][j])
    score = inputData[i][2]
    eitem = inputData[i][1]
    if score<425:
        d['1'][0]+=1
        d['1'][1]+=eitem
    # elif score<500:
    #     d['2'][0] += 1
    #     d['2'][1] += eitem
    elif score<600:
        d['3'][0] += 1
        d['3'][1] += eitem
    elif score<710:
        d['4'][0] += 1
        d['4'][1] += eitem
errorlist=[]
errorlist.append(round(d['1'][1]/d['1'][0],4))
# errorlist.append(round(d['2'][1]/d['2'][0],4))
errorlist.append(round(d['3'][1]/d['3'][0],4))
errorlist.append(round(d['4'][1]/d['4'][0],4))
# print(errorlist)

画出errorlist,并保存图

#第一步,取出一张白纸
fig=plt.figure(1)
#第二步,确定绘图范围,由于只需要画一张图,所以我们将整张白纸作为绘图的范围
ax1=plt.subplot(111)
#第三步,整理我们准备绘制的数据
# data=np.array([15,20,18,100])
#第四步,准备绘制条形图,思考绘制条形图需要确定那些要素
#1、绘制的条形宽度
#2、绘制的条形位置(中心)
#3、条形图的高度(数据值)
width=0.5
x_bar=np.arange(3)
print(x_bar)
#第五步,绘制条形图的主体,条形图实质上就是一系列的矩形元素,我们通过plt.bar函数来绘制条形图
rect=ax1.bar(left=x_bar,height=errorlist,width=width,color="lightblue")
#第六步,向各条形上添加数据标签
for rec in rect:
    x=rec.get_x()
    height=rec.get_height()
    ax1.text(x+0.1,1.02*height,str(height))
#第七步,绘制x,y坐标轴刻度及标签,标题
ax1.set_xticks(x_bar)
ax1.set_xticklabels(("0~425", "425~600", "600~710"))
ax1.set_ylabel("均差",FontProperties=font)
ax1.set_xlabel("成绩分布区间",FontProperties=font)
ax1.set_title("成绩预测均差分布图",FontProperties=font)
ax1.grid(False)
ax1.set_ylim(0,180)
plt.show()
fig.savefig('errorbar.png', dpi=600)

 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值