#方法1:用matplotlib.gridspec.GridSpec自定义网格大小,然后添加子图fig.add_subplot
import matplotlib.pyplot as plt
import matplotlib.gridspec
x1 = np.linspace(0.0, 5.0)
x2 = np.linspace(0.0, 2.0)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)
gs = matplotlib.gridspec.GridSpec(3,2, width_ratios=[1,1.4],
height_ratios=[1,3,1])
fig = plt.figure()
ax1 = fig.add_subplot(gs[:,0])
# ax1.plot([1,3,2,4])
ax1.plot(x1, y1, '-og', ms=3)
ax2 = fig.add_subplot(gs[1,1])
# ax2.plot([1,3,2,4])
ax2.plot(x2, y2, '-ob', ms=3)
plt.show()
#方法二:利用fig.add_axes添加子图,同时指定子图axes的大小(传入比例大小参数) import numpy as np import matplotlib.pyplot as plt fig = plt.figure() w,h = fig.get_size_inches() div = np.array([w,h,w,h]) # define axes in by rectangle [left, bottom, width, height], numbers in inches ax1 = fig.add_axes(np.array([.7, .7, 1.8, 3.4])/div) ax1.plot(x1, y1, '-og', ms=3) ax2 = fig.add_axes(np.array([3, 1.4, 3, 2])/div) ax2.plot(x2, y2, '-ob', ms=3) plt.show()
#方法三:利用plt.axes(rect1)生成合适大小的子图,传入比例大小参数。 import numpy as np import matplotlib.pyplot as plt '''调整 matplotlib 子图的大小''' x1 = np.linspace(0.0, 5.0) x2 = np.linspace(0.0, 2.0) y1 = np.cos(2 * np.pi * x1) * np.exp(-x1) y2 = np.cos(2 * np.pi * x2) plt.figure() rect1 = [0.14, 0.35, 0.77, 0.6] # [左, 下, 宽, 高] 规定的矩形区域 (全部是0~1之间的数,表示比例) rect2 = [0.14, 0.05, 0.77, 0.2] ax1 = plt.axes(rect1) ax1.plot(x1, y1, '-og', ms=3) ax2 = plt.axes(rect2) ax2.plot(x2, y2, '-ob', ms=3) plt.show()
# 方法三:方法同上(直接传入数据) import numpy as np import matplotlib.pyplot as plt x1 = np.linspace(0.0, 5.0) x2 = np.linspace(0.0, 2.0) y1 = np.cos(2 * np.pi * x1) * np.exp(-x1) y2 = np.cos(2 * np.pi * x2) plt.axes([0.14, 0.35, 0.77, 0.6]) plt.plot(x1, y1, 'yo-') plt.axes([0.14, 0.05, 0.77, 0.2]) plt.plot(x2, y2, 'r.-') plt.show()
总结:
用matplotlib可视化过程中,如何自定义子图的大小?
(1) 用matplotlib.gridspec.GridSpec自定义网格大小,然后添加子图fig.add_subplot
(2)利用fig.add_axes添加子图,同时指定子图axes的大小(传入比例大小参数)
(3)用plt.axes(rect1)生成合适大小的子图,传入比例大小参数。
参考链接:
https://www.bbsmax.com/A/x9J277AW56/
https://www.it1352.com/2297738.html



