Python和Matplotlib:创建两个不同大小的子图

Mat*_*NNZ 4 python matplotlib

我有一个脚本创建一个或两个图表,具体取决于是否满足一个特定条件.基本上,到目前为止我所做的是以下内容:

import matplotlib.pyplot as plt

list1 = [1,2,3,4]
list2 = [4,3,2,1]
somecondition = True
plt.figure(1) #create one of the figures that must appear with the chart
ax = plt.subplot(211) #create the first subplot that will ALWAYS be there
ax.plot(list1) #populate the "main" subplot
if somecondition == True:
   ax = plt.subplot(212) #create the second subplot, that MIGHT be there
   ax.plot(list2) #populate the second subplot
plt.show()
Run Code Online (Sandbox Code Playgroud)

这段代码(带有正确的数据,但我所做的这个简单版本无论如何都是可执行的)生成了两个相同大小的子图,一个在另一个之上.但是,我想得到的是以下内容:

  • 如果某个条件为True,则两个子图都应出现在图中.因此,我希望第二个子图比第一个子图小1/2;
  • 如果某个条件为False,那么只应显示第一个子图,我希望它的大小为所有图形(在不显示第二个子图的情况下不留空空间).

我很确定这只是调整两个子图的大小,甚至可能是参数211和212(我不明白它们代表什么,因为我是Python的新手并且无法找到明确的解释在网上).有没有人知道如何以一种简单的方式调整子图的大小,与子图的数量以及图的整个大小成比例?为了便于理解,您还可以编辑我附加的简单代码以获得我正在寻找的结果吗?提前致谢!

zha*_*hen 7

这个解决方案满足吗?

import matplotlib.pyplot as plt

list1 = [1,2,3,4]
list2 = [4,3,2,1]
somecondition = True
plt.figure(1) #create one of the figures that must appear with the chart

if not somecondition:
    ax = plt.subplot(111) #create the first subplot that will ALWAYS be there
    ax.plot(list1) #populate the "main" subplot
else:
    ax = plt.subplot(211)
    ax.plot(list1)
    ax = plt.subplot(223) #create the second subplot, that MIGHT be there
    ax.plot(list2) #populate the second subplot
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

如果你需要相同的宽度,但有一半的高度,更好地使用matplotlib.gridspec,请参考这里

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

list1 = [1,2,3,4]
list2 = [4,3,2,1]
somecondition = True
plt.figure(1) #create one of the figures that must appear with the chart

gs = gridspec.GridSpec(3,1)

if not somecondition:
    ax = plt.subplot(gs[:,:]) #create the first subplot that will ALWAYS be there
    ax.plot(list1) #populate the "main" subplot
else:
    ax = plt.subplot(gs[:2, :])
    ax.plot(list1)
    ax = plt.subplot(gs[2, :]) #create the second subplot, that MIGHT be there
    ax.plot(list2) #populate the second subplot
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


Nor*_*bők 5

看来你正在寻找这个:

if somecondition:
    ax = plt.subplot(3,1,(1,2))
    ax.plot(list1)
    ax = plt.subplot(3,1,3)
    ax.plot(list2)
else:
    plt.plot(list1)
Run Code Online (Sandbox Code Playgroud)

神奇的数字是nrows,ncols,plot_number,请参阅文档.因此3,1,3将创建3行,1列,并将绘制到第三个单元格中.缩写就是313.

可以使用元组作为plot_number,因此您可以创建一个位于第一个和第二个单元格中的图:3,1,(1,2).