In matplotlib with PdfPages, how do I set the plotting area to only use the top half of a full page?

1.8k views Asked by At

With the code below, I'd like to create a two page pdf, with both pages in standard portrait (8.5 inches wide and 11 inches tall).

How can I set the plot area of the second page to only use the top half of the page? I tried using the commented out line of code but that just cut the page size in half rather than leaving the page size in tact and halving the plot area.

Thanks!

import numpy as np

import matplotlib
matplotlib.use("PDF")
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages

import seaborn as sns
sns.set()

xs = np.linspace(-np.pi, np.pi, 40)
ys = np.sin(xs)
with PdfPages('multipage_pdf.pdf') as pdf:
    plt.figure(figsize=(8.5, 11))
    plt.plot(xs, ys, '-')
    plt.title('Page One')
    pdf.attach_note('Full page')
    pdf.savefig()
    plt.close()

    plt.figure(figsize=(8.5, 11))
#    plt.figure(figsize=(8.5, 5.5))
    plt.plot(xs, ys, '-')
    plt.title('Page Two')
    pdf.attach_note('Want top half of page')
    pdf.savefig()
    plt.close()
2

There are 2 answers

1
Steve Schulist On

With the help from others, here's the solution (pretty straightforward).

import numpy as np

import matplotlib
matplotlib.use("PDF")
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages

import seaborn as sns
sns.set()

xs = np.linspace(-np.pi, np.pi, 40)
ys = np.sin(xs)
with PdfPages('multipage_pdf.pdf') as pdf:
    plt.figure(figsize=(8.5, 11))
    plt.plot(xs, ys, '-')
    plt.title('Page One')
    pdf.attach_note('Full page')
    pdf.savefig()
    plt.close()

    fig = plt.figure(figsize=(8.5, 11))
    ax = fig.add_subplot(211)
    ax.plot(xs, ys, '-')
    ax.set_title('Page Two')
    pdf.attach_note('Want top half of page')
    pdf.savefig()
    plt.close()
0
r-beginners On

After much research, I did not find the best solution. So I drew multiple graphs and wrote the code with the second one as a blank graph. I'm sorry if my answer will reduce the chances of getting answers from others.

import numpy as np
import matplotlib
matplotlib.use("PDF")
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages

import seaborn as sns
sns.set()

xs = np.linspace(-np.pi, np.pi, 40)
ys = np.sin(xs)

pp = PdfPages('SaveMultiPDF.pdf')

fig = plt.figure(figsize=(8.5, 11))
ax = fig.add_subplot(111)
ax.plot(xs, ys, '-')
ax.set_title('Page One')
pp.attach_note('Full page')
plt.savefig(pp, format='pdf')
fig.clf()

fig1 = plt.figure(figsize=(8.5, 11))
ax1 = fig1.add_subplot(211)
ax1.plot(xs, ys, '-')
ax1.set_title('Page Two')
pp.attach_note('Want top half of page')
# blank graph
sns.set_style('white')
ax2 = fig1.add_subplot(212)
ax2.plot([], [])
ax2.axis('off')
plt.savefig(pp, format='pdf')
fig1.clf()

pp.close()