效果展示:
-
subplot(222)子画布
-
一个图形中多个轴域通过subplot(2,2), axs[0,0]子画布的表示
-
同时显示出两个图形,每个图形都有多个子图,通过subplot2grid定义子图位置
代码示例
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
import pandas as pd
mpl.rcParams['font.sans-serif'] = ['SimHei']
mpl.rcParams['axes.unicode_minus'] = False
########################################
# 1. subplot(222)子画布,适用:多个固定大小的网格
# subplot的基本使用
fig = plt.figure() # 创建图像对象
ax1 = plt.subplot(221)
ax2 = plt.subplot(222)
'''
subplot的编码规则是:
xyz == x * y的网格中 第z个轴域
也可表示为(x, y, z),如果有一个值超过了9,则必须用这用表示方式
按照从左向右,从上向下表示
ax1和ax2表示位置为2*2网格的第一行的第一个和第二个网格,此时ax3表示2*1的第二行
正好覆盖了2*2的第二行,如果ax3=(211)的话会覆盖第一行,整个图形只有ax3显示
'''
ax3 = plt.subplot(212)
ax1.plot([1,2])
ax2.plot([2,1])
ax3.plot([1,4])
########################################
# 2. 一个图形中多个轴域通过subplot(2,2), axs[0,0]子画布的表示
x = np.arange(10)
y2 = np.random.randint(1,10,10)
y1 = np.random.randint(1,10,100)
# 设置画布的大小及
fig, axs = plt.subplots(2,2,figsize=(8,8))
# 2.2 定义子画布方式二:此时ax1,ax2,ax3对应子图131,132,133
# fig, (ax1,ax2,ax3) = plt.subplot(1,3)
axs[0,0].hist(y1,bins=x,color='r')
# 设置子图的属性
axs[0,0].set(title='hist',xlabel='type',ylabel='amount')
axs[0,1].plot(x,y2)
axs[0,1].set(title='plot',xlabel='x',ylabel='y')
axs[1,0].scatter(x,y2)
axs[1,0].set(title='plot',xlabel='x',ylabel='y')
axs[1,1].bar(x,y2)
axs[1,1].set(title='plot',xlabel='x',ylabel='y')
# 设置全部图像的总标题
plt.suptitle('Subplot Demo')
plt.tight_layout(pad=3,w_pad=1.0,h_pad=1.0)
########################################
# 3. 同时显示出两个图形,每个图形都有多个子图,通过subplot2grid定义子图位置,特点:非固定大小块的图像
x = np.linspace(1,10,10)
y = np.random.randint(0,10,10)
# 第一个图像
fig = plt.figure(1, figsize=(12,9))
ax1 = plt.subplot2grid( (3,3), (0,0) )
ax2 = plt.subplot2grid( (3,3), (0,1), colspan=2 ) # 列跨两行
ax3 = plt.subplot2grid( (3,3), (1,0), colspan=2, rowspan=2 ) # 行列各跨两行
ax4 = plt.subplot2grid( (3,3), (1,2), rowspan=2 )
ax1.plot(x,y)
ax2.scatter(x,y,s=50*x*y,alpha=0.3)
ax3.bar(x,y)
ax4.hist(y,bins=x)
plt.suptitle('First Figure')
plt.tight_layout(pad=5, w_pad=0.5, h_pad=1.0)
# 第二个图像
plt.figure(2, figsize=(12,5))
plt.subplot(131)
plt.bar(x,y)
plt.subplot(1,3,2)
plt.scatter(x,y)
plt.subplot(1,3,3)
plt.hist(y,bins=x)
plt.suptitle('Second Figure')
plt.tight_layout(pad=5, w_pad=0.5, h_pad=1.0)
plt.show()