您的位置:首页 > 编程语言 > PHP开发

数据分析第四节课Matplotlib作业

2020-08-20 11:24 477 查看

练习一

绘制班级的身高分布图形
height = [160,163,175,180,176,177,168,189,188,177,174,170,173,181]
代码如下:

from matplotlib import pyplot as plt
import  matplotlib
font = {'family':'SimHei',
'weight':'bold',
'size':12
}
matplotlib.rc("font",**font)    #设置字体格式

height = [160,163,175,180,176,177,168,189,188,177,174,170,173,181]
cha = max(height) - min(height)    #求极差
bins = round(cha)//5              #求组数
plt.hist(height,bins,rwidrh=0.8)
plt.xlabel('身高')
plt.ylabel('人数')
plt.title('身高直方图')
plt.savefig('身高分布直方图')
plt.show()

绘图如下:

练习二

使用栅栏对象绘制子图长宽比例不同的综合图如下:

代码如下:

from matplotlib import pyplot as plt
import matplotlib
import random
font = {'family':'SimHei',
'weight':'bold',
'size':12
}
matplotlib.rc("font",**font)   #设置全局字体格式
fig = plt.figure()
width = (3,1)		#设置第0列和第1列子图宽度比例
height = (1,2)		#设置第0列和第1列子图高度比例
#创建2*2的栅栏对象
gs =fig.add_gridspec(2,2,width_ratios=width,height_ratios=height)
#绘制条形图
ax1 = fig.add_subplot(gs[0,0])		#添加子图
x1 = ["变身特工","美丽人生","鲨海逃生","熊出没"]
y1 = [2358,399,2358,362]
ax1.bar(x1,y1)
ax1.set_xlabel('电影')
ax1.set_ylabel('票房')
ax1.set_title('电影票房数据')
#绘制直方图
ax2 = fig.add_subplot(gs[1,0])
x2 = [160,166,175,180,176,177,168,189,188,177,174,170,169,181]
ax2.hist(x2,round(max(x2)-min(x2))//5)
ax2.set_xlabel('身高')
ax2.set_ylabel('人数')
ax2.set_title('各身高区间的人数及其体重')
#绘制散点图与直方图共用一个子图
ax3 = ax2.twinx()
x3 = [random.randint(160,190) for i in range(10)]
y3 = [random.randint(0,100) for i in range(10)]
ax3.scatter(x3,y3,color='g')
ax3.set_ylabel('体重')
#绘制线形图
ax4 = fig.add_subplot(gs[1,1])
ax4.plot(range(10),range(10))
fig.subplots_adjust(wspace=0.5,hspace=0.5)   #调整子图间距
plt.savefig('综合图')
plt.show()

绘得图如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: