Matplotlib根据在for循环中生成的图形创建子图

时间:2019-01-28 09:47:13

标签: python loops matplotlib figure subplot

我是python的新手,尽管在这里研究了许多子图线程 我仍然找不到解决方案。

我正在尝试生成一个2页pdf文件,每页2个子图。 在我的代码中,我加载了4组数据(每个文件中2列数字),然后为每组创建一个绘图。 它工作正常,但我无法将这些图分布在两个图形(页面)中,每页2个图。

这是我正在尝试做的,但我没有得到带有2个子图的图形,而是仅获得了第二个图(我现在尝试仅获得具有2个子图的一页)。

你们中的任何人有什么建议吗?

from matplotlib import pyplot as plt
import numpy as np
from matplotlib.backends.backend_pdf import PdfPages

with PdfPages ('subplot.pdf') as pdf:

    for i in range(1,5):
        x = []
        y = []
        with open('data{}.txt'.format(i)) as data:
            data = data.readlines()
            for row in data:
                x.append(row.split()[0])
                y.append(row.split()[1])

            fig = plt.figure()
            plt.plot(x,y)
            plt.xticks([])
            plt.yticks([])
            plt.title('Data {}'.format(i))
    fignum = plt.get_fignums()
    print(fignum)

    plt.subplot(2,1,1)
    plt.figure(fignum[0])
    plt.subplot(2,1,2)
    plt.figure(fignum[1])

    pdf.savefig()
    plt.close()

1 个答案:

答案 0 :(得分:0)

您可能误解了the multipage pdf example。您将需要在每页上创建一个图形,并在每个图形上添加两个轴。为了更好地理解,也许此伪代码更有用:

loop over pages
    create figure
    loop over axes inside of figure
        plot to axes
    save figure

实际上,它可能看起来像这样:

from matplotlib import pyplot as plt
import numpy as np
from matplotlib.backends.backend_pdf import PdfPages

def get_data(n):
    #return np.loadtxt('data{}.txt'.format(n), unpack=True)
    return np.random.rand(2,10)


with PdfPages ('subplot.pdf') as pdf:
    # loop for pages
    for i in [1,3]:
        # create a figure
        fig, axes = plt.subplots(nrows=2)
        # loop over axes
        for j in [0,1]:
            x,y = get_data(i+j)

            axes[j].plot(x,y)
            axes[j].set(xticks=[], yticks=[])
            axes[j].set_title('Data {}'.format(i+j))
        # append figure to pdf
        pdf.savefig(fig)
        plt.close()

enter image description here