AI智能
改变未来

数据分析第四节课Matplotlib作业


练习一

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

from matplotlib import pyplot as pltimport  matplotlibfont = {\'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 pltimport matplotlibimport randomfont = {\'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()

绘得图如下:

赞(0) 打赏
未经允许不得转载:爱站程序员基地 » 数据分析第四节课Matplotlib作业