python - 在每个子图之间以适当的间距绘制子图

标签 python python-3.x matplotlib

<分区>

我需要绘制 6 个数据子图,目前我在间距方面遇到了问题。我的图需要在每个子图的顶部有一个带有样本索引的标题。我的问题是由于间距不当,绘图可视化很困难。下面是一个可重现的例子:

import matplotlib.pyplot as pp
import matplotlib.pyplot as plt
from numpy import random
    x1 = random.randint(2000, size=(125))
    x2 = random.randint(1000, size=(125))
    plt.subplot(2, 3, 1)
    pp.plot(x1, label="Class 1", color='red')
    pp.plot(x2, label="Class 2", color='blue')
    leg = pp.legend(loc='lower center', bbox_to_anchor=[0.5, 1.1], ncol=2)
    pp.title("Sample 7")
    
    
    
    x1 = random.randint(2000, size=(125))
    x2 = random.randint(1000, size=(125))
    plt.subplot(2, 3, 2)
    pp.plot(x1, color='red')
    pp.plot(x2, color='blue')
    leg = pp.legend(loc='lower center', bbox_to_anchor=[0.5, 1.1], ncol=2)
    pp.title("Sample 2")
    
    
    
    
    x1 = random.randint(2000, size=(125))
    x2 = random.randint(1000, size=(125))
    plt.subplot(2, 3, 3)
    pp.plot(x1, color='red')
    pp.plot(x2, color='blue')
    leg = pp.legend(loc='lower center', bbox_to_anchor=[0.5, 1.1], ncol=2)
    pp.title("Sample 3")
    
    
    
    
    
    x1 = random.randint(2000, size=(125))
    x2 = random.randint(1000, size=(125))
    plt.subplot(2, 3, 4)
    pp.plot(x1, color='red')
    pp.plot(x2, color='blue')
    pp.title("Sample 9")
    leg = pp.legend(loc='lower center', bbox_to_anchor=[0.5, 1.1], ncol=2)
    
    
    
    
    x1 = random.randint(2000, size=(125))
    x2 = random.randint(1000, size=(125))
    plt.subplot(2, 3, 5)
    pp.plot(x1, color="red")
    pp.plot(x2, color="blue")
    pp.title("Sample 11")
    leg = pp.legend(loc='lower center', bbox_to_anchor=[0.5, 1.1], ncol=2)
    
    
    
    x1 = random.randint(2000, size=(125))
    x2 = random.randint(1000, size=(125))
    plt.subplot(2, 3, 6)
    pp.plot(x1, color="red")
    pp.plot(x2, color="blue")
    pp.title("Sample 13")
    leg = pp.legend(loc='lower center', bbox_to_anchor=[0.5, 1.1], ncol=2)
    plt.show() 

我想知道我需要添加/进行哪些更改才能使数据值轴具有适当的间距并在不与其他子图重叠的情况下显示,而不是将那些空标签放在每个子图的底部,替换它情节外顶部的每个子情节都有一个标签

最佳答案

我认为您忘记了使用 tight_layout() 来处理这些问题。在绘图之前添加它。复制最后几行代码:

plt.subplot(2, 3, 6)
pp.plot(x1, color="red")
pp.plot(x2, color="blue")
pp.title("Sample 13")
leg = pp.legend(loc='lower center', bbox_to_anchor=[0.5, 1.1], ncol=2)
plt.tight_layout()
plt.show() 

输出:

enter image description here

关于python - 在每个子图之间以适当的间距绘制子图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73355475/

相关文章:

python - 如何正确绘制情节?

python - 如何在数据库之前格式化变量以避免错误

python - 如何在 Django 中为 Chatterbot 指定自定义语料库路径?

python - 汽车跟踪级联::Typeerror 整数到 float

python - python静态方法是否比实例方法消耗更少的内存

python - 理解 Python 的 Base64 解码字节表示

python - 根据名称将多个文件从单个文件夹移动到多个文件夹

python - 防止 pandas read_csv 将第一行视为列名的标题

python - 使用 python/pandas 将数据标准化并绘制为堆积条形图

python - matplotlib 中更漂亮的默认绘图颜色