简体   繁体   English

如何使用 Matplotlib 在图中添加多个直方图?

[英]How to add multiple histograms in a figure using Matplotlib?

I'm using matplotlib to plot many histograms in one plot successfully:我在一个 plot 中成功使用了 matplotlib 到 plot 许多直方图:

import matplotlib.pyplot as plt
import numpy as np

np.random.seed(1)

for i in range(0, 6):
    data = np.random.normal(size=1000)
    plt.hist(data, bins=30, alpha = 0.5)
plt.show()

在此处输入图像描述

However, I wish to export this plot in a pdf, using PdfPages.但是,我希望使用 PdfPages 在 pdf 中导出此 plot。 I want to add each histogram in a separate page, which I successfully do like this:我想在单独的页面中添加每个直方图,我成功地这样做了:

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

np.random.seed(1)

fig = []
with PdfPages("exported_data.pdf") as pdf:
    for i in range(0, 6):
        data = np.random.normal(size=1000)
        fig.append(plt.hist(data, bins=30, alpha = 0.5))
        pdf.savefig(fig[i])
        plt.close()

But I want another, 7th page with all the plots in one figure as shown above.但我想要另一个第 7 页,其中所有图都在一个图中,如上所示。 How do I add many histograms in the same figure (so I can then add in the pdf page)?如何在同一个图中添加许多直方图(这样我就可以在 pdf 页面中添加)? I see many tutorials on how to plot a grid of histograms within a figure but I haven't found one with all the histograms in one plot added to a figure.我看到很多关于如何 plot 一个图中的直方图网格的教程,但我还没有找到一个将 plot 中的所有直方图添加到图中的教程。

Thanks, Stam谢谢,斯塔姆

You can run the loop to plot all histograms together (your first code snippet) after having run the loop to plot them separately (your second code snippet).在将循环分别运行到 plot (您的第二个代码片段)之后,您可以将循环运行到 plot 所有直方图(您的第一个代码片段)。 Here is an example where the random arrays are saved in the datasets list during the first loop to be able to plot them together in the second loop.这是一个示例,其中随机 arrays 在第一个循环期间保存在datasets列表中,以便能够在第二个循环中将它们一起 plot 。 This solution works by using plt.gcf() which returns the current figure.此解决方案通过使用plt.gcf()返回当前图形来工作。

import numpy as np               # v 1.19.2
import matplotlib.pyplot as plt  # v 3.3.4
from matplotlib.backends.backend_pdf import PdfPages

np.random.seed(1)

datasets = []
with PdfPages("exported_data.pdf") as pdf:
    # Plot each histogram, adding each figure to the pdf
    for i in range(6):
        datasets.append(np.random.normal(size=1000))
        plt.hist(datasets[i], bins=30, alpha = 0.5)
        pdf.savefig(plt.gcf())
        plt.close()
    # Plot histograms together using a loop then add the completed figure to the pdf
    for data in datasets:
        plt.hist(data, bins=30, alpha = 0.5)
    pdf.savefig(plt.gcf())
    plt.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM