import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei']#解决中文乱码
plt.rcParams['axes.unicode_minus']=False#解决符号乱码
#创建数据
sex=["男","女"]
df1=pd.DataFrame({
"names":["student"+str(i) for i in range(1,32) ],
"sex":[sex[np.random.randint(2)] for i in range(31) ],
"python":np.random.randint(60,101,31),
"spark":np.random.randint(60,90,31),
"linux":np.random.randint(60,98,31)
})
# #1) 用折线图呈现python,spark,linux的前5名
# pythontop5=df1["python"].sort_values(ascending=False)[:5]
# sparktop5=df1["spark"].sort_values(ascending=False)[:5]
# linuxtop5=df1["linux"].sort_values(ascending=False)[:5]
# print(pythontop5)
# nums=range(1,6)
# plt.plot(nums,pythontop5,color='red',marker='o',linestyle='-')
# plt.plot(nums,sparktop5,color='green',marker='o',linestyle='--')
# plt.plot(nums,linuxtop5,color='blue',marker='o',linestyle='--')
# labels=["第%s名"%x for x in range(1,6)]
# plt.xticks(nums,labels)#设置X轴的标签
# plt.title("分数TOP5")#设置标题
# plt.xlabel(["python前五名","spark前五名","linux前五名"])# 设置x轴的标签o
# plt.ylabel("分数")# 设置y轴的标签
# plt.show()#显示图形
#2) 用堆积柱状图呈现总分前5名的各科成绩,
# 横轴显示学生的姓名,纵轴显示分数,共3个图例。总分标注出来
df1["总分"]=df1["python"]+df1["spark"]+df1["linux"]
top5=df1.sort_values(by=["总分"],ascending=False)[:5]
nums=np.arange(1,10,2)
plt.bar(nums,top5["python"],width=0.3)
plt.bar(nums,top5["spark"],bottom=top5["python"],width=0.3)
plt.bar(nums,top5["linux"],bottom=top5["python"]+top5["spark"],width=0.3)
plt.xticks(nums,top5["names"])
plt.legend(["python","spark","linux"])
plt.ylim(0,350)
plt.ylabel("分数")
plt.title("总分TOP5")
for x,y in zip(nums,top5["总分"]):
plt.text(x,y+3,"%s分"%y)
plt.show()
#3) 用并列柱状图分别呈现男生和女生的python,spark,linux的平均分
gs=df1.groupby(by="sex").mean()
nums=np.arange(0,4,2)
print(gs)
w=0.5
plt.bar(nums,gs["python"],color="red",width=w)
plt.bar(nums+w,gs["spark"],color="green",width=w)
plt.bar(nums+w*2,gs["linux"],color="blue",width=w)
plt.xticks(nums,["女生","男生"])
plt.xlabel("性别")
plt.ylabel("分数")
plt.ylim(0,120)
plt.legend(["python平均分","spark平均分","linux平均分"])
plt.show()
pandas自己创建且用图表展示前几名的成绩
最新推荐文章于 2023-11-29 20:58:30 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)