设置画布大小
matplotlib 模块中采用figure函数设置自定义大小的画布,调用方式如下所示:
- matplotlib.pyplot.figure(num=None, figsize=None, dpi=None, facecolor=None, edgecolor=None, frameon=True, FigureClass=<class ‘matplotlib.figure.Figure’>, clear=False, **kwargs)[source]
在画图之前首先设置figure对象,使得后面的图形输出在这块规定了大小的画布上。参数num用于返回指定 id 的figure对象,如果此参数没有提供,则一个新的figure对象将被创建。参数figsize用于设置画布的宽高,单位为英尺。参数dpi用于设置分辨率。参数facecolor用于设置背景色,edgecolor用于设置边框颜色。
绘制多个子图
在 matplotlib 中, 一个figure对象可以包含多个子图, 可以使用subplot()快速绘制, 其调用形式如下:
- # 第一种:整个绘图区域被分成 nrows 行和 ncols 列,index 表示第几个图
- subplot(nrows, ncols, index, **kwargs)
- # 第二种:pos 是三位数的整数,其中第一位是行数,第二位是列数,第三位是子图的索引
- subplot(pos, **kwargs)
- # 第三种:添加子图 ax
- subplot(ax)
subplot()的第二种调用方式的代码示例如下:
- import matplotlib.pyplot as plt
- import numpy as np
- t = np.arange(0.0, 2.0, 0.01)
- s1 = np.sin(2*np.pi*t)
- s2 = np.sin(4*np.pi*t)
- plt.subplot(211) # 绘图区域被分为 2 行 1 列,接下来绘制第一幅图
- plt.plot(t, s1)
- ax2 = plt.subplot(212) # 绘制第二幅图
- plt.plot(t, 2*s1)
- plt.show()
输出图像如下所示:
案例代码
- import matplotlib.pyplot as plt
- import numpy as np
- #初始数据
- labels = ['none', 'primary', 'junior', 'senior', 'specialties', 'bachelor', 'master'] # 标签
- womenCount = [2052380, 11315444, 20435242, 7456627, 3014264, 1972395, 185028]
- birthMen = [2795259, 12698141, 13982478, 2887164, 903910, 432333, 35915]
- birthWomen = [2417485, 11000637, 11897674, 2493829, 786862, 385718, 32270]
- liveMen = [2717613, 12477914, 13847346, 2863706, 897607, 429809, 35704]
- liveWomen = [2362007, 10854232, 11815939, 2480362, 783225, 384158, 32136]
-
- # 请在此添加实现代码 #
- # ********** Begin *********#
- #数据处理
- avePerson = []
- ratio = []
- #不同受教育程度育龄妇女生育子女的平均个数统计方法
- def N1():
- for i in range(len(labels)):
- da = (birthMen[i] + birthWomen[i]) / womenCount[i]
- avePerson.append(da)
- N1()
- #不同受教育程度育龄妇女生育子女的存活比例统计方法
- def N2():
- for i in range(len(labels)):
- da = ((liveMen[i]+liveWomen[i])/(birthMen[i]+birthWomen[i])*100)
- ratio.append(da)
- N2()
-
- index = np.arange(len(labels))
-
- #设置画布尺寸
- plt.figure(figsize = [14,5])
- #划分绘图区域
- ax1 = plt.subplot(121)
- plt.xticks(index,labels)
- plt.plot(avePerson,'r-')
-
- ax2 = plt.subplot(122)
- plt.xticks(index,labels)
- plt.plot(ratio,'b-')
-
- plt.savefig('picture/step4/fig4.png')
- plt.show()
- # ********** End **********#
运行结果