非转载,详细解释python参数fig.add_subplot(111),一遍就懂
看了下CSDN原本已有的博客,写的都不是很清楚。就自己稍微写下,以后也方便查看。
文档的描述
链接: link.
add_subplot(nrows, ncols, index, **kwargs)
Either a 3-digit integer or three separate integers describing the position of the subplot. If the three integers are nrows, ncols, and index in order, the subplot will take the index position on a grid with nrows rows and ncols columns. index starts at 1 in the upper left corner and increases to the right.
大致意思就是输入 三位数字,abc,根据abc将原图划分成a行,b列。那么就会将原图划分成a*b个子图,然后c就是我们的下标。我们通过c来指定展示我们要的子图。下面贴几个例子帮助理解。
例子1
这里就可以理解为做了一个长为10,宽为5的figure,然后add_subplot(111),a=1,b=1,c=1,表示把他的行和列都分为1份,其实就是保持不变,所以子图只有1*1=1个,那么当我们最后选择展示第1个子图时,其实就是展示他本身。
f = plt.figure(figsize=(10,5))
f.add_subplot(111)
例子2
现在我们把相同的图分成四份,进行比较.
这里就可以理解为做了一个长为10,宽为5的figure,然后add_subplot(221),a=2,b=2,c=1,表示把他的行和列都分为2份,其实就是保持不变,所以子图只有2*2=4个,那么当我们最后选择展示第1个子图时,其实就是展示左上角第一个子图(注意顺序,从左往右,从上往下)。
f = plt.figure(figsize=(10,5))
f.add_subplot(221)
例子3
或许这样还是容易造成困扰,结合下面这个例子,就比较容易理解了.第一张图我们把figure分成4份,并且全部展示,那么其实最后四个子图拼起来后的图就和例子1一样。
第二张图我们选择展示figure的第一张子图和第四张子图,那么得到的就是左上角的第一张图和右下角的最后一张图。
f = plt.figure(figsize=(10,5))
f.add_subplot(221)
f.add_subplot(222)
f.add_subplot(223)
f.add_subplot(224)
f = plt.figure(figsize=(10,5))
f.add_subplot(221)
f.add_subplot(224)
注意
对于f.add_subplot(abc)来说,c是大于等于1小于等于ab,这样符合常理,毕竟总共就ab的子图。
另外当a,b,c大于等于10时,可以采用f.add_subplot(a,b,c)的写法。