在一張畫布上定義多張子圖:
import matplotlib.pyplot as plt import numpy as np from matplotlib import gridspec
生成幾個隨機點:
random_cp = np.random.random_integers(1, 100, (100, 2)) random_nums = np.random.random_integers(1, 100, 100) random_cp1 = np.random.random_integers(1, 100, (100, 2)) random_nums1 = np.random.random_integers(1, 100, 100)
1、使用add_subplot
通過add_subplot就可以實現子圖的划分:
先是通過plt.figure()創建畫布,之后再通過add_subplot()在畫布上創建不同的區域。
其中add_subplot()的參數,類似221就是將畫布分為2行2列的也就是2×2的區域,使用第1個區域。
fig1 = plt.figure() ax1 = fig1.add_subplot(221) ax2 = fig1.add_subplot(222) ax3 = fig1.add_subplot(223) ax4 = fig1.add_subplot(224) ax1.plot(range(len(random_nums)), random_nums) ax3.scatter(random_cp[:, 0], random_cp[:, 1]) ax4.plot(range(len(random_nums1)), random_nums1) ax2.scatter(random_cp1[:, 0], random_cp1[:, 1]) plt.show()
2、使用GridSpec
先是通過gridspec.GridSpec()創建區域,參數5,5的意思就是每行五個,每列五個,最后就是一個5×5的畫布,相比於add_subplot(),使用網格布局的話可以更加靈活的控制占用多少空間。
gs = gridspec.GridSpec(5,5) fig1 = plt.figure() ax1 = fig1.add_subplot(gs[0:2, 0:2]) ax2 = fig1.add_subplot(gs[3:5, 0:2]) ax3 = fig1.add_subplot(gs[0:2, 3:5]) ax4 = fig1.add_subplot(gs[3:5, 3:5]) ax1.plot(range(len(random_nums)), random_nums) ax3.scatter(random_cp[:, 0], random_cp[:, 1]) ax4.plot(range(len(random_nums1)), random_nums1) ax2.scatter(random_cp1[:, 0], random_cp1[:, 1]) ax1.plot(range(len(random_nums)), random_nums) ax3.scatter(random_cp[:, 0], random_cp[:, 1]) ax4.plot(range(len(random_nums1)), random_nums1) ax2.scatter(random_cp1[:, 0], random_cp1[:, 1]) plt.show()
感興趣的掃描下方二維碼:備注:“人工智能” 哦