【发布时间】:2014-01-16 11:47:01
【问题描述】:
我有一个脚本,它根据是否满足一个特定条件来创建一个或两个图表。基本上,到目前为止,我正在做的事情如下:
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()
这段代码(使用正确的数据,但我所做的这个简单版本无论如何都是可执行的)生成两个相同大小的子图,一个在另一个之上。但是,我想得到的是以下内容:
- 如果 somecondition 为 True,则两个子图都应出现在图中。因此,我希望第二个子图比第一个小 1/2;
- 如果 somecondition 是 False,那么应该只出现第一个子图,我希望它的大小与所有图一样(不要留下空白,以防第二个子图不会出现)。
我很确定这只是调整两个子图大小的问题,甚至可能通过参数 211 和 212 (我不明白它们代表什么,因为我是 Python 新手,找不到网上有明确的解释)。有谁知道如何以简单的方式调节子图的大小,与子图的数量以及图形的整个大小成正比?为了更容易理解,您能否编辑我附加的简单代码以获得我正在寻找的结果?提前致谢!
【问题讨论】:
-
好的,至于第二点(即,如果 somecondition 是 False 完全调整子图的大小)我已经做了以下解决方法:
if somecondition = True: nsub = 111; else: nsub = 211; ax = plt.subplot(nsub)但是,一个更优雅的解决方案将受到高度赞赏,并且主要问题(即第二个子图的 1/2 比例)尚未解决:/
标签: python matplotlib