Figure 和 Axes
使用 matplotlib 绘制图表时,图表是由 figure 和 axes 两个元素所构成,这篇教学会介绍 figure 和 axes 的用法和观念。
快速导览
本篇使用的 Python 版本为 3.7.12,所有范例可使用 Google Colab 实作,不用安装任何软件 ( 参考:使用 Google Colab )
什么是 figure?
figure 表示“画布”,表示 atplotlib 绘制图表的空间,在绘制图表时,要先创建一个画布,才能在加入各种元素,储存或输出图片时,也都是以 figure 为单位进行储存或输出。
什么是 axes?
axes 表示“座标系统”,如果是二维图表,axes 会包含两个座标轴 ( axis )、如果是三维图表,axes 会包含三个座标轴 ( axis ),依此类推,在一个 figure 之中,可以设定多个 axes,下图呈现 figure、axes 和 asix 的关系。
建立 figure 的方法
matplotlib 绘制图表时,可以使用“隐性”或“显性”建立 figure 的方法,隐性建立表示执行某些方法时,会自动产生 figure,显性建立则需要透过 figure 的方法建立。
隐性建立 figure
下方的程序码执行 plt.plot(x) 时,会判断 figure 对象是否存在,如果不存在,就会自动建立一个 figure 对象,并且在这个 figure 里建立一个 axes 座标系统。
import matplotlib.pyplot as plt x = [1,2,3,4,5] plt.plot(x) plt.show()显性建立 figure
使用 .figure() 方法建立画布,能绘制不同的图表,或针对 figure 进行更精细的设定。
import matplotlib.pyplot as plt x = [1,2,3,4,5] f = plt.figure() plt.subplot() plt.plot(x) plt.show()
figure 的两种使用方法
使用显性建立 figure 时,有两种 figure 的使用方法:
plt.figure()
import matplotlib.pyplot as plt x = [1,2,3,4,5] f = plt.figure() plt.subplot() plt.plot(x) plt.show()fig, ax = plt.subplots()
import matplotlib.pyplot as plt x = [1,2,3,4,5] fig, ax = plt.subplots() ax.plot(x) plt.show()
延伸阅读
微信扫码关注
抖音扫码关注