matplotlib(6)-- subplot创建; subplot2grid ;GridSpec ;不同subplot坐标轴共享

 1 import matplotlib.pyplot as plt
 2 
 3 # example 1:
 4 ###############################
 5 plt.figure(figsize=(6, 4))
 6 # plt.subplot(n_rows, n_cols, plot_num)
 7 plt.subplot(2, 2, 1)
 8 plt.plot([0, 1], [0, 1])
 9 
10 plt.subplot(2, 2, 2)
11 plt.plot([0, 1], [0, 2])
12 
13 plt.subplot(2, 2, 3)
14 plt.plot([0, 1], [0, 3])
15 
16 plt.subplot(2, 2, 4)
17 plt.plot([0, 1], [0, 4])
18 
19 plt.tight_layout()
20 
21 # example 2:
22 ###############################
23 plt.figure(figsize=(6, 4))
24 # figure splits into 2 rows, 1 col, plot to the 1st sub-fig
25 plt.subplot(2, 1, 1)
26 plt.plot([0, 1], [0, 1])
27 # figure splits into 2 rows, 3 col, plot to the 4th sub-fig
28 plt.subplot(2, 3, 4)
29 plt.plot([0, 1], [0, 2])
30 # figure splits into 2 rows, 3 col, plot to the 5th sub-fig
31 plt.subplot(2, 3, 5)
32 plt.plot([0, 1], [0, 3])
33 # figure splits into 2 rows, 3 col, plot to the 6th sub-fig
34 plt.subplot(2, 3, 6)
35 plt.plot([0, 1], [0, 4])
36 
37 plt.tight_layout()
38 
39 plt.show()

 

 

 1 import matplotlib.pyplot as plt
 2 import matplotlib.gridspec as gridspec
 3 
 4 # method 1: subplot2grid
 5 ##########################
 6 plt.figure()
 7 #整个figure为 3*3
 8 ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=3)  #ax1起始是第一行第一列,占一行三列
 9 #plt.subplot2grid(shape, loc, rowspan=1, colspan=1, fig=None, **kwargs)
10 #参数解释:
11 # shape : sequence of 2 ints
12 # loc : sequence of 2 ints
13 # rowspan : int    Number of rows for the axis to span to the right.
14 # colspan : int    Number of columns for the axis to span downwards.
15 # rowspan、colspan默认值为1
16 ax1.plot([1, 2], [1, 2])
17 ax1.set_title('ax1_title')
18 ax2 = plt.subplot2grid((3, 3), (1, 0), colspan=2)   #ax2起始为第二行第一列,占一行两列
19 ax3 = plt.subplot2grid((3, 3), (1, 2), rowspan=2)   #ax3起始为第二行第三列,占两行一列
20 ax4 = plt.subplot2grid((3, 3), (2, 0))  #ax4起始为第三行第一列,占一行一列,散点图
21 ax4.scatter([1, 2], [2, 2])
22 ax4.set_xlabel('ax4_x')
23 ax4.set_ylabel('ax4_y')
24 ax5 = plt.subplot2grid((3, 3), (2, 1)) #ax5起始为第三行第二列,占一行一列
25 
26 # method 2: gridspec
27 #########################
28 plt.figure()
29 gs = gridspec.GridSpec(3, 3)
30 # use index from 0
31 ax6 = plt.subplot(gs[0, :])
32 ax7 = plt.subplot(gs[1, :2])
33 ax8 = plt.subplot(gs[1:, 2])
34 ax9 = plt.subplot(gs[-1, 0])
35 ax10 = plt.subplot(gs[-1, -2])
36 
37 #这里理解矩阵切片相关知识很好理解,矩阵切片相关知识,参考博客  https://blog.csdn.net/u014453898/article/details/73430907
38 
39 # method 3: easy to define structure
40 ####################################
41 f, ((ax11, ax12), (ax13, ax14)) = plt.subplots(2, 2, sharex = True, sharey = True)      #不同subplot共享x,y轴
42 ax11.scatter([1,2], [1,2])
43 
44 plt.tight_layout()
45 plt.show()

 

posted @ 2019-07-26 09:20  小伙郭  阅读(1391)  评论(0编辑  收藏  举报