Figure 参数设定
使用 matplotlib 绘制图表时,可以透过设定 figure 的参数,设定画布的尺寸 ( 改变图表尺寸 )、边框或底色,这篇教学将会介绍 figure 相关参数的设定方法。
本篇使用的 Python 版本为 3.7.12,所有范例可使用 Google Colab 实作,不用安装任何软件 ( 参考:使用 Google Colab )
figure 的常用参数
下方列出使用 figure() 方法时常用的参数。
| 参数 | 默认 | 说明 |
|---|---|---|
| num | None | 画布的唯一标记,如果不指定 num,每次执行 figure() 方法时会自动增加 1,表示会产生新的画布。 |
| figsize | (6,4) | 画布长宽尺寸,单位为“英寸”。 |
| dpi | 100 | 画布分辨率,表示一英寸里有几个像素。 |
| facecolor | white | 背景色。 |
| edgecolor | white | 外框颜色。 |
| linewidth | 0 | 外框粗细。 |
| frameon | True | 是否显示外框和背景色,设定 False 表示不显示。 |
加入 figure 参数,绘制图表
下方的程序码,会产生一个默认样式的图表。
import matplotlib.pyplot as plt
x = [1,2,3,4,5]
fig = plt.figure()
plt.subplot()
plt.plot(x)
plt.show()
下方的程序码,加入边框颜色、背景颜色、边框宽度和长宽尺寸的参数设定,就会产生不同画布样式的图表。
import matplotlib.pyplot as plt
x = [1,2,3,4,5]
fig = plt.figure(edgecolor='#f00', facecolor='#ff0', linewidth=5, figsize=(8,3))
plt.subplot()
plt.plot(x)
plt.show()
下方的程序码,使用了三次 figure() 方法,且没有设定 num 参数,结果就会画出三张不同的图表 ( 因为会产生三个 num 不同的画布 )
import matplotlib.pyplot as plt
x = [1,2,3,4,5]
y = [5,4,3,2,1]
z = [2,2,2,2,2]
fig1 = plt.figure()
plt.subplot(2,2,1)
plt.plot(x)
fig2 = plt.figure()
plt.subplot(2,2,1)
plt.plot(y)
fig3 = plt.figure()
plt.subplot(2,2,1)
plt.plot(z)
plt.show()
将上方的例子加入 num=1 的参数设定,就可以让图表绘制在同一个画布上。
import matplotlib.pyplot as plt
x = [1,2,3,4,5]
y = [5,4,3,2,1]
z = [2,2,2,2,2]
fig1 = plt.figure(num=1)
plt.subplot(2,2,1)
plt.plot(x)
fig2 = plt.figure(num=1)
plt.subplot(2,2,1)
plt.plot(y)
fig3 = plt.figure(num=1)
plt.subplot(2,2,1)
plt.plot(z)
plt.show()
微信扫码关注
抖音扫码关注