首页 > 解决方案 > 绘制子图时,直方图未显示在 pdf 中

问题描述

我正在尝试在 pdf 文件中为我的数据框中的每个变量绘制时间序列和直方图。每个动作单独工作,但在同一页面中对它们进行子图绘制时,直方图未显示。知道我做错了什么吗?这是我的代码:

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

    for i in range(df.shape[1]):
        fig = plt.figure()
        #time series
        plt.subplot(2, 1, 1)
        ax1 = df.iloc[:,i].plot(color='blue', grid=True, label='lab')
        plt.title(df.columns.values[i])

        #histograms
        plt.subplot(2, 1, 2)
        hist=df.hist(df.columns.values[i])
        plt.plot()

        pdf.savefig(fig)
        plt.close()

标签: pythonmatplotlibhistogrampdfpages

解决方案


我不太确定我是否真的可以重现您的错误 - 但是,我会在您的代码中优化一些内容,也许您可​​以通过以下示例考虑一下:

with PdfPages('test.pdf') as pdf:
    for c in df:
        fig, axs = plt.subplots(2)
        #time series
        fig.suptitle(c)
        df[c].plot(color='blue', grid=True, label='lab', ax=axs[0])

        #histogram
        hist=df.hist(c, ax=axs[1])

        pdf.savefig(fig)
        #plt.close()

主要提示:

  1. 无需迭代数据框列的值
  2. 用于plt.subplots()一个图中的多个绘图
  3. 我删除plt.plot()了 - 它没有做任何事情

推荐阅读