Python 和 Matplotlib : creating two subplots with different sizes

标签 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()

此代码(具有正确的数据,但我所做的这个简单版本无论如何是可执行的)生成两个相同大小的子图,一个在另一个之上。但是,我想得到的是:

  • 如果某个条件为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()

enter image description here

如果您需要相同宽度但一半高度,最好使用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()

enter image description here

关于Python 和 Matplotlib : creating two subplots with different sizes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21160914/

相关文章:

python - python 运算符重载是如何工作的

python - matplotlib fill_ Between 留下间隙

python - 绘制每列随时间的观察结果(数据可用性)

python - 如何在复杂的pandas groupby中绘制图表?

python - 使用 matplotlib 箭头进行缩放

python - 如何将 __iter__ 添加到动态类型?

python - 事后清理存储在源存储库中的 virtualenv 中的 .pyc 文件吗?

python - 如何转换为 ctypes 中的常量?

python - 在 Pandas 中查找包含另一列的行中的特定值的列名称

python - 在python和matplotlib生成的PPTX中为图片(绘图)添加边框