创建图形区域
在进行数据分析处理的时候,我们常常要进行数据可视化,此时在Python中我们就要用到一个非常强大的画图包matplotlib
。画图我们常常用到的是其中的pyplot
。
import matplotlib.pyplot as plt
pyplot.figure
figure
函数的作用即为新建一个图像区域,函数主要的参数及解释如下:
figure(num=None, figsize=None, dpi=None, facecolor=None, edgecolor=None, frameon=True)
-
num
:图像编号(整数)或名称(字符串) -
fidsize
:图像尺寸 -
dpi
:图像分辨率 -
facecolor
:背景色 -
edgecolor
:边缘颜色 -
frameon
:图像边框(默认有边框)
返回值:.figure.Figure
默认参数
plt.figure()
plt.plot([0,1],[0,1])
自定义参数
plt.figure(figsize=(10,6),frameon=False)
plt.plot([0,1],[0,1])
plt.figure(facecolor='#B9E0ED')
plt.plot([0,1],[0,1])
通过figure划分子区域:add_subplot和add_axes
add_subplot
figure.add_subplot
的语法结构和下面要说的pyplot.subplot
的基本一样:
add_subplot(nrows, ncols, index, **kwargs)
add_axes
add_axes
的语法结构:
- add_axes(rect, projection=None, polar=False, **kwargs)
rect
是一个四元数组来表示一个矩形,表示为[left, bottom, width, height]
,其中(left, bottom)
是表示这个矩形左下角的坐标,(width, height)
表示矩形的长和宽。这样可以在图形区域的相应位置的矩形的。
fig = plt.figure(figsize=(8,6))
plt.plot()
ax = fig.add_axes([0.1,0.5,0.3,0.3])
两个函数同时使用看看结果:
fig = plt.figure(figsize=(8,6))
plt.plot()
fig.add_subplot(2,2,4)
fig.add_axes([0.1,0.5,0.3,0.3])
pyplot.subplots
subplots
同样也是创建新的图像,与figure
不同的是subplots可以创建多个子区域,并返回一个可以自定义的子区域数据结构Axes
。基本语法如下:
subplots(nrows=1, ncols=1, sharex=False, sharey=False)
-
nrows
,ncols
:表示划分成多少行多少列的区域 -
sharex
,sharey
:表示是否使用相同的x轴还是y轴
除以上这些参数以外还可以使用figure
中的参数。
返回值:.figure.Figure
, .axes.Axes
前者是有关画图的最上级的数据结构;后者是一个或一组具有数据空间的图像区域
fig, ax = plt.subplots(2,2, figsize=(8,6))
import numpy as np
np.shape(ax)
(2, 2)
这个例子当中我们新建了一个划分成的图像区域,可以理解成一个图像矩阵,而每个图像对应着一个.axes.Axes
数据结构,因此命令输出的ax
也将是一个包含.axes.Axes
的结构.
fig = plt.figure(num=1,figsize=(10,6))
plt.plot([0,1],[1,0])
fig2, ax2 = plt.subplots(figsize=(5,3), num=2)
plt.plot([0,1],[0,1])
我们发现当用figure
新建一个图像时,plt.plot
是在这个新建的图像上进行操作,而plt.subplots
则又重新新建了一个新的坐标图。此时如果再运行subplots
,所画的图像将在新生成的图像区域中。
那么问题来了,如果我新画的直线还想画在大图里怎么操作?
我们知道,
plot
是在当前“激活”的图像中进行画图,那么如果要回到大图中画,则要重新“激活” figure 1。
fig = plt.figure(num=1,figsize=(10,6))
plt.plot([0,1],[1,0])
fig2, ax2 = plt.subplots(figsize=(5,3), num=2)
plt.figure(1) #重新激活 figure 1
plt.plot([0,1],[0,1])
pyplot.subplot
subplot
注意不要和subplots
混淆,subplot
是在现有的figure中加入子图的基本语法:
- subplot(nrows, ncols, index, **kwargs)
- subplot(pos, **kwargs)
- subplot(ax)
返回值:.Axes
nrows
, ncols
, index
的意思是,把现有的图形区域划分为的几个子区域,从第一排开始,从左至右数第位置被“激活”
下面用几个例子来说明subplot
的用法
plt.figure(figsize=(10,6))
ax1 = plt.subplot(221)
plt.plot([0,1],[0,1])
ax2 = plt.subplot(2,2,4)
plt.plot([0,1],[1,0])
fig, ax = plt.subplots(2,2, figsize=(8,6))
ax3 = plt.subplot(ax[1,0])
plt.plot([0,1],[0,1])
ax3 = plt.subplot(222)
plt.plot([0,1],[1,0])
所以subplot
可以在figure
生成的图像区域内划分子区域并在目标位置画图,或者在subplots
已经划分好的子区域内相应位置画图。
问题来了,如果subplot
的位置和在subplots
所划分的区域并不匹配会出现什么结果?我们通过下面这个了例子说明这个问题。
fig, ax = plt.subplots(2,2, figsize=(10,8)) #分为2*2
plt.subplot(333) # 分成3*3取第3个位置
plt.plot([0,1],[0,1])
可以发现通过subplot
被激活的位置的图会把subplots
下相应位置的图给覆盖掉。