- 已知实验中学举行了高二期中模拟考试,考试后分别计算了全体男生、女生各科的平均成绩,统计结果如表(一)所示。
表(一) z
学科 | 平均成绩(男) | 平均成绩(女) |
语文 | 85.5 | 94 |
数学 | 91 | 82 |
英语 | 72 | 89.5 |
物理 | 59 | 62 |
化学 | 66 | 49 |
生物 | 55 | 53 |
按照以下要求绘制图表:
- 绘制柱形图。柱形图的x轴为学科,y轴为平均成绩。
2.绘制堆积柱形图。堆积柱形图的x轴为学科,y轴为平均成绩。
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#解决中文乱码
plt.rcParams['font.sans-serif']=['SimHei']
#引入数据
df = pd.read_excel('全校高二男生、女生的平均成绩.xlsx')
#设置画布的大小
plt.figure(figsize=(10,6))
bar_width = 0.3 #柱子的宽度
#数据
x = np.array([0,1,2,3,4,5]) #array 用于 x+bar_width 的顺利运行,将列表转化为数组,不能直接引入【‘学科’】
y1 = df['平均成绩(男)']
y2 = df['平均成绩(女)']
#设置x,y轴的标签
plt.ylabel('平均成绩')
plt.xlabel('学科')
#设置标题
plt.title('全校高二男生、女生的平均成绩')
#绘制柱状图
plt.bar(x,y1,bar_width,color='c',alpha=0.5)
plt.bar(x+bar_width,y2,bar_width,color='b',alpha=0.5)
#设置坐标轴刻度
data=df['学科']
plt.xticks(x,data)
#添加文本标签
for a,b in zip(x,y1):
plt.text(a,b,format(b,','),ha='center',va='bottom',fontsize=8)
for a,b in zip(x,y2):
plt.text(a+bar_width,b,format(b,','),ha='center',va='bottom',fontsize=8)
#设置图例
plt.legend(['平均成绩(男)','平均成绩(女)'])
plt.show()
- 在上题的基础上定制柱形图,具体要求如下:
- 设置y轴的标签为“平均成绩(分)”;
- 设置x轴的刻度标签位于两组柱形中间;
- 添加标题为“高二男生、女生的平均成绩”;
- 添加图例;
- 向每个柱形的顶部添加注释文本,标注平均成绩。
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#解决中文乱码
plt.rcParams['font.sans-serif']=['SimHei']
#引入数据
df = pd.read_excel('全校高二男生、女生的平均成绩.xlsx')
#设置画布的大小
plt.figure(figsize=(10,6))
bar_width = 0.3 #柱子的宽度
#数据
x = np.array([0,1,2,3,4,5]) #array 用于 x+bar_width 的顺利运行,将列表转化为数组,不能直接引入【‘学科’】
y1 = df['平均成绩(男)']
y2 = df['平均成绩(女)']
#设置x,y轴的标签
plt.ylabel('平均成绩(分)')
plt.xlabel('学科')
#设置标题
plt.title('全校高二男生、女生的平均成绩')
#绘制柱状图
plt.bar(x-0.5*bar_width,y1,bar_width,color='c',alpha=0.5)
plt.bar(x+0.5*bar_width,y2,bar_width,color='b',alpha=0.5)
#设置坐标轴刻度
data=df['学科']
plt.xticks(x,data)
#添加文本标签
for a,b in zip(x,y1):
plt.text(a-0.5*bar_width,b,format(b,','),ha='center',va='bottom',fontsize=8)
for a,b in zip(x,y2):
plt.text(a+0.5*bar_width,b,format(b,','),ha='center',va='bottom',fontsize=8)
#设置图例
plt.legend(['平均成绩(男)','平均成绩(女)'])
plt.show()
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#解决中文乱码
plt.rcParams['font.sans-serif']=['SimHei']
#引入数据
df = pd.read_excel('全校高二男生、女生的平均成绩.xlsx')
#设置画布的大小
plt.figure(figsize=(10,6))
bar_width = 0.3 #柱子的宽度
#数据
x = np.array([0,1,2,3,4,5]) #array 用于 x+bar_width 的顺利运行,将列表转化为数组,不能直接引入【‘学科’】
y1 = df['平均成绩(男)']
y2 = df['平均成绩(女)']
#设置x,y轴的标签
plt.ylabel('平均成绩')
plt.xlabel('学科')
#设置标题
plt.title('全校高二男生、女生的平均成绩')
# 绘制堆积柱形图
plt.bar(x, y1, width=bar_width)
plt.bar(x, y2, bottom=y1,width=bar_width)
#设置坐标轴刻度
data=df['学科']
plt.xticks(x,data)
#添加文本标签
for a,b in zip(x,y1):
plt.text(a,b,format(b,','),ha='center',va='bottom',fontsize=8)
for a,b in zip(x,y2):
plt.text(a,b,format(b,','),ha='center',va='bottom',fontsize=8)
#设置图例
plt.legend(['平均成绩(男)','平均成绩(女)'])
plt.show()
#创作不易,点点关注下次不迷路