【问题标题】:histogram not showing in pdf when subploting绘制子图时,直方图未显示在 pdf 中
【发布时间】:2018-10-21 20:46:39
【问题描述】:

我正在尝试在 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()

【问题讨论】:

    标签: python matplotlib histogram pdfpages


    【解决方案1】:

    我不太确定我是否真的可以重现你的错误 - 但是,我会在你的代码中优化一些东西,也许你可以通过这个例子来考虑一下:

    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() - 它没有任何作用

    【讨论】:

    • 感谢您的回答,代码更容易阅读和高效。我是 python 新手,所以我仍然掌握它!另外,我不知道为什么,但我尝试了你的代码,现在我不再遇到问题了,所以也特别感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-16
    • 1970-01-01
    • 2019-09-24
    • 1970-01-01
    • 1970-01-01
    • 2016-08-29
    • 2021-09-05
    相关资源
    最近更新 更多