from pylab import *
import matplotlib.gridspec as gridspec
"""
subplot()函数的参数中,除最后一维的其它维表示子图的大小,最后一维表示当前子图在图像中的位置,如:在2*2的网格里,第四个子图为(2,2,4)
创建横跨多个位置的子图用gridspec实现
参数 默认值 描述
num 1 图像的数量
figsize figure.figsize 图像的长和宽(英寸)
dpi figure.dpi 分辨率(点/英寸)
facecolor figure.facecolor 绘图区域的背景颜色
edgecolor figure.edgecolor 绘图区域边缘的颜色
frameon True 是否绘制图像边缘
"""
def four_sub_graph():
# 绘制上下左右4个子图
"""
# 方式一
fig = plt.figure(figsize=(10,10),dpi=80,facecolor='red')
ax1 = fig.add_subplot(2,2,1)
ax2 = fig.add_subplot(2,2,2)
ax3 = fig.add_subplot(2, 2, 3)
ax4 = fig.add_subplot(2, 2, 4)
ax1.plot()
ax2.plot()
ax3.plot()
ax4.plot()
show()
"""
# 方式二
for i in range(1, 5):
subplot(2, 2, i)
xticks([]), yticks([])
text(0.5, 0.5, f'subplot(2,2,{i})', ha='center', va='center', size=20, alpha=0.5)
show()
def mix_sub_graph():
"""
绘制多个子图,其中某些子图横跨多个子图
:return:
"""
# gridspec的用法,可以是图像横跨多个坐标
G = gridspec.GridSpec(3, 3)
axes_1 = subplot(G[0, :])
xticks([]), yticks([])
text(0.5, 0.5, 'Axes 1', ha='center', va='center', size=24, alpha=.5)
axex_2 = subplot(G[1, :-1])
xticks([]), yticks([])
text(0.5, 0.5, 'Axes 2', ha='center', va='center', size=24, alpha=.5)
axex_3 = subplot(G[1:, -1])
# 确定了这个子图的位置之后,就可以直接在上面画图,直接创建了下个新的子图
x = np.linspace(-np.pi, np.pi, 256, endpoint=True)
c, s = np.cos(x), np.sin(x)
plt.plot(x, c)
plt.plot(x, s)
# xticks([]), yticks([])
# text(0.5, 0.5, 'Axes 3', ha='center', va='center', size=24, alpha=.5)
axex_4 = subplot(G[-1, 0])
xticks([]), yticks([])
'''
text()函数用于在图像上的绑定位置加上一些文本,用于注释
'''
text(0.5, 0.5, 'Axes 4', ha='center', va='center', size=24, alpha=.5)
axes_5 = subplot(G[-1, -2])
xticks([]), yticks([])
text(0.5, 0.5, 'Axes 5', ha='center', va='center', size=24, alpha=.5)
# plt.savefig('../figure/gridspec.png', dpi=64)
show()
four_sub_graph()
mix_sub_graph()
函数four_sub_graph():
函数mix_sub_graph():