先上效果:
实际工作中,有时候需要查询某位学生的年级排名情况,老式的图都是低绘到高的,这里用echarts改为这种图,直观地展示出各科排名情况。
目录
1.数据准备
原始的数据是下图这种excel表格形式的,我们获取的数据通常是以这种形式出现的:特征有班级、姓名、各学科、总分等,每一行都是一位学生的具体信息。
接下来需要将所有学科+所有学科排名统计好,放在一个大表格中。
import pandas as pd
couresList = ['语文','数学','英语','物理','化学','历史','政治','总分'] #所有 学科名
rankingList = list(i+'排名' for i in couresList) # 学科排名 列表
def getBaseDf():
dfFormPath = pd.DataFrame(pd.read_excel(excelFilePath)) # 将原始数据表转化成dataframe,原始数据表就是上面写的excel
return dfFormPath
def getAllCourseRanking():
# 班级 姓名 各科 各科排名,按各科进行排名的df
dfFormPath = getBaseDf() # 将原始数据表转化成dataframe
for i in couresList:
dfFormPath = dfFormPath.sort_values(by=i, ascending=False) # 按本学科进行排名,得到新的表格
dfFormPath = dfFormPath.reset_index(drop=True) # 索引按总分排名重新布置
newColTitle = i + '排名'
dfFormPath[newColTitle] = dfFormPath.index + 1 # 添加科目排名列,名次按index+1来算
dfFormPath[newColTitle] = dfFormPath[newColTitle].astype(int) # 将排名数据类型都转化为整整数类型
return dfFormPath # 得到的数据表包括了所有学科的成绩和排名
函数getAllCourseRanking()获得的dataframe形式如下:
它包括了原来表格的内容,以及新加入的语文排名、数学排名等数据。
由于echarts使用的数据不是dataframe,而是列表,所以要写一个函数获取要查询的x轴和y轴的列表:
def getStuAllRank(name):
dfData = getAllCourseRanking()
getData = dfData.loc[dfData['姓名'] == name] # 获取姓名是要查找的详细数据
getDataGet = getData[rankingList] #获取各科排名
xList = rankingList
yList = getDataGet.values.tolist()[0] #获取各科排名的数值列表
return xList, yList #结果用函数后面[0]或者[1]获取
这样,我们就能通过下面的代码获取x轴和y轴要显示的数据:
dfDataX = getStuAllRank('王子睿')[0]
#值为:['语文排名', '数学排名', '英语排名', '物理排名', '化学排名', '历史排名', '政治排名', '总分排名']
dfDataY = getStuAllRank('王子睿')[1]
#值为:[22, 16, 42, 88, 95, 88, 105, 39]
2.绘制图表
接下来用echarts绘制数据表,要注意引入相应的库:
from pyecharts.charts import Bar
import streamlit_echarts
from pyecharts import options as opts
import streamlit as st
接下来写一个绘制表格的函数:
def stuClassRanking(stuName):
if stuNameIsIn(stuName):
bar = Bar()
bar.add_xaxis(dataTo.getStuAllRank(stuName)[0])
bar.add_yaxis(stuName + ' 年级排名', dataTo.getStuAllRank(stuName)[1])
bar.set_global_opts(yaxis_opts=opts.AxisOpts(is_inverse=True)) #反转y轴,y轴改为自上而下依此增大
bar.set_global_opts(xaxis_opts=opts.AxisOpts(position="top")) #设置x轴的位置在顶部
bar.set_global_opts(opts.InitOpts(width='900px', height='500px'))
bar.set_series_opts(opts.LabelOpts(position="insideBottom")) #设置数据标签的位置在条形的底部
streamlit_echarts.st_pyecharts(
bar
)
else:
pass
return
3.在streamlit中显示
stuClassRanking(’王子‘)
# 终端输入 streamlit run Main.py
最终效果:
参考文献: