2022年 11月 5日

Python多子图绘制

设置画布大小

matplotlib 模块中采用figure函数设置自定义大小的画布,调用方式如下所示:

  1. 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()快速绘制, 其调用形式如下:

  1. # 第一种:整个绘图区域被分成 nrows 行和 ncols 列,index 表示第几个图
  2. subplot(nrows, ncols, index, **kwargs)
  3. # 第二种:pos 是三位数的整数,其中第一位是行数,第二位是列数,第三位是子图的索引
  4. subplot(pos, **kwargs)
  5. # 第三种:添加子图 ax
  6. subplot(ax)

subplot()的第二种调用方式的代码示例如下:

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3.  
  4. t = np.arange(0.0, 2.0, 0.01)
  5. s1 = np.sin(2*np.pi*t)
  6. s2 = np.sin(4*np.pi*t)
  7.  
  8. plt.subplot(211) # 绘图区域被分为 2 1 列,接下来绘制第一幅图
  9. plt.plot(t, s1)
  10. ax2 = plt.subplot(212) # 绘制第二幅图
  11. plt.plot(t, 2*s1)
  12. plt.show()

输出图像如下所示:

案例代码

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. #初始数据
  4. labels = ['none', 'primary', 'junior', 'senior', 'specialties', 'bachelor', 'master'] # 标签
  5. womenCount = [2052380, 11315444, 20435242, 7456627, 3014264, 1972395, 185028]
  6. birthMen = [2795259, 12698141, 13982478, 2887164, 903910, 432333, 35915]
  7. birthWomen = [2417485, 11000637, 11897674, 2493829, 786862, 385718, 32270]
  8. liveMen = [2717613, 12477914, 13847346, 2863706, 897607, 429809, 35704]
  9. liveWomen = [2362007, 10854232, 11815939, 2480362, 783225, 384158, 32136]
  10. # 请在此添加实现代码 #
  11. # ********** Begin *********#
  12. #数据处理
  13. avePerson = []
  14. ratio = []
  15. #不同受教育程度育龄妇女生育子女的平均个数统计方法
  16. def N1():
  17. for i in range(len(labels)):
  18. da = (birthMen[i] + birthWomen[i]) / womenCount[i]
  19. avePerson.append(da)
  20. N1()
  21. #不同受教育程度育龄妇女生育子女的存活比例统计方法
  22. def N2():
  23. for i in range(len(labels)):
  24. da = ((liveMen[i]+liveWomen[i])/(birthMen[i]+birthWomen[i])*100)
  25. ratio.append(da)
  26. N2()
  27. index = np.arange(len(labels))
  28. #设置画布尺寸
  29. plt.figure(figsize = [14,5])
  30. #划分绘图区域
  31. ax1 = plt.subplot(121)
  32. plt.xticks(index,labels)
  33. plt.plot(avePerson,'r-')
  34. ax2 = plt.subplot(122)
  35. plt.xticks(index,labels)
  36. plt.plot(ratio,'b-')
  37. plt.savefig('picture/step4/fig4.png')
  38. plt.show()
  39. # ********** End **********#

运行结果