matplotlib使用GridSpec调整子图位置大小 (非对称的子图)

用matplotlib.pyplot的subplots命令能够很方便的画对称的子图,可是若是要画非对称的子图(以下)就须要用GridSpec命令来控制子图的位置和大小:
html

而上图的结构能够用一下两种方式画:python

import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

fig = plt.figure(1)
gs = GridSpec(3, 3)

ax1 = plt.subplot(gs[0, :])
ax2 = plt.subplot(gs[1, :2])
ax3 = plt.subplot(gs[1:, 2])
ax4 = plt.subplot(gs[2, 0])
ax5 = plt.subplot(gs[2, 1])

或者函数

ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=3)
ax2 = plt.subplot2grid((3, 3), (1, 0), colspan=2)
ax3 = plt.subplot2grid((3 ,3), (1, 2), rowspan=2)
ax4 = plt.subplot2grid((3, 3), (2, 0))
ax5 = plt.subplot2grid((3, 3), (2, 1))

更多间隔设置能够参考gridspec的官方文档。spa

PS:若是是读取图片做为子图的话建议用Pillow包的Image函数读取,而非自带的imread函数,对图像的调整会方便不少:code

ax1 = fig.add_subplot(gs[:, 0])
img = Image.open("your image")
ax1.imshow(img)
相关文章
相关标签/搜索