1

I am trying to plot multiple figures to one PDF but it generates corrupt PDF.

import sys, os, pandas as pd, numpy as np, matplotlib.pyplot as plt
import pylab, scipy.stats as stats, calendar
from matplotlib.backends.backend_pdf import PdfPages
def plotLineGraph(df):
    fig = plt.figure()
    ax = fig.add_subplot(211)
    df.plot(ax=ax)
    ax = plt.subplot(111)
    return fig

pp = PdfPages(r'C:\myPLOT.pdf')
for ii in [1,2,3,4]:
    df = pd.DataFrame({'x': np.rand(500), 'y':np.rand(500)})
    pp.savefig(plotGraph(df))
pp.close()

How should I modify the above code so that I get the 4 plots successfully in one PDF file.

1 Answer 1

2

There are several typos in your code.

  1. The function is called plotLineGraph not plotGraph
  2. numpy has no rand, it is numpy.random.rand instead.
  3. You create a superfluous axes via ax = plt.subplot(111). Remove that line.

Finally consider that writing to C:\ directly is not allowed in some windows systems. In total this would give:

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

def plotLineGraph(df):
    fig = plt.figure()
    ax = fig.add_subplot(211)
    df.plot(ax=ax)
    return fig

pp = PdfPages(r'D:\myPLOT.pdf')
for ii in [1,2,3,4]:
    df = pd.DataFrame({'x': np.random.rand(500), 'y':np.random.rand(500)})
    pp.savefig(plotLineGraph(df))
pp.close()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.