-1

I am trying to plot in a pdf file a time series and a histogram for each of the variables in my data frame. Each action works separately, but when subploting both of them in the same page, the histogram is not showing. Any idea what I am doing wrong? Here's my code:

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()
Magdalena
  • 1
  • 3

1 Answers1

0

I'm not quite sure if I could really reproduce your error - however, there are some things I would optimize in your code, perhaps you can think about it with this example:

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()

Main hints:

  1. No need for iterating over the values of the columns of the dataframe
  2. Use plt.subplots() for multiple plots in one figure
  3. I deleted plt.plot() - it doesn't do anything
SpghttCd
  • 10,510
  • 2
  • 20
  • 25
  • Thank you for your answer, the code is much easier to read and efficient. I am new to python, so I am still getting the hang of it! Also, I am not sure why, but I tried your code and now I am not having the problem anymore, so special thanks for that too. – Magdalena Oct 22 '18 at 12:19