我有一个脚本可以创建一个或两个图表,具体取决于是否满足某个特定条件。基本上,到目前为止我正在做的是:
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()
此代码(具有正确的数据,但我所做的这个简单版本无论如何是可执行的)生成两个相同大小的子图,一个在另一个之上。但是,我想得到的是:
- 如果某个条件为True,则两个子图都应出现在图中。因此,我希望第二个子图比第一个小 1/2;
- 如果 somecondition 为 False,那么应该只出现第一个子图,我希望它的大小与所有图形相同(如果第二个子图不会出现,则不留下空白空间) ).
我很确定这只是调整两个子图的大小的问题,甚至可能是参数 211 和 212(我不明白它们代表什么,因为我是 Python 的新手并且找不到网上还没有明确的解释)。有谁知道如何以简单的方式调节子图的大小,与子图的数量以及图形的整个大小成比例?为了让它更容易理解,你能否也请编辑我附加的简单代码以获得我正在寻找的结果?提前致谢!
这个解决方案是否满足?
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()
如果您需要相同宽度但一半高度,最好使用matplotlib.gridspec
, reference here
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()