Matplotlib.pyplot - 如何将直方图保存在变量中供以后访问?

Matplotlib.pyplot - how to save a histogram in a variable for later access?

由于数据访问模式,我需要将各种直方图保存在一个 Python 列表中,然后访问它们以作为多页 PDF 的一部分输出。

如果我在创建直方图后立即将它们保存到我的 PDF 中,我的代码就可以正常工作:

def output_histogram_pdf(self, pdf):
        histogram = plt.hist(
            x=[values], bins=50)
        plt.xlabel(xlabel)
        plt.ylabel(ylabel)
        plt.title(title)

        if isinstance(pdf, PdfPages):
            pdf.savefig()

但如果我改为将它们保存到列表中以便以后可以操纵顺序,我 运行 就会遇到麻烦。

histogram_list.append(histogram)

以后

for histogram in histogram_list:
            plt.figure(histogram)
            pdf.savefig()

这不起作用。我要么保存错了东西,要么我不知道如何正确打开我保存的内容。

我花了相当长的时间在谷歌上搜索一个有效的解决方案,但没有结果,但是涉及的很多术语都非常模糊,以至于我在搜索结果中遇到了大量不同类型的问题。任何帮助将不胜感激,谢谢!

简答

您可以使用plt.gcf()

创建图形时,在设置 xlabel、ylabel 和标题后,将图形附加到直方图列表。

histogram_list.append(plt.gcf())

稍后您可以遍历列表并调用 savefig。

长答案

plt.hist 没有 return 这个数字 object。然而,数字object可以使用gcf(Get Current Figure)获得。

如果您不想使用当前图形,您可以随时使用 plt.figure or plt.subplot.

自己创建图形

无论哪种方式,由于您已经绘制了直方图并设置了图形的标签,因此您希望将图形附加到列表中。

选项 1:使用 gcf

    histogram = plt.hist(
        x=[values], bins=50)
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    plt.title(title)
    histogram_list.append(plt.gcf())

选项 2:创建您自己的图形

    figure = plt.figure(figsize=(a,b,))
    # draw histogram on figure
    histogram_list.append(figure)

每个 histogram(n,bins,patches) 组成,其中 n 是每个 bin 的值,bins 是 bin 边(1 多于 n),patches是创作酒吧的艺术家。

最简单的是,尝试将每个直方图绘制为

for histogram in histogram_list:
    n = histogram[0]
    bins = histogram[1]
    plt.plot(bins[:-1], n, '-', ds='steps-pre')