12

I would like to align my suptitle in the top left-hand corner on each page of the multiple PDF document I am trying to create, however, it doesn't seem to be doing as I try to ask. The below script produces the suptitle in the top and centre. I cannot figure out what I am doing wrong:

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

pdf = PdfPages('TestPDF.pdf')

Countries = ['Argentina', 'Australia']

for country in Countries:
    fig = plt.figure(figsize=(4, 5))
    fig.set_size_inches([10, 7])
    plt.suptitle(country, horizontalalignment='left', verticalalignment='top',
                 fontsize = 15)
    x = 1000
    plt.plot(x, x*x, 'ko')
    pdf.savefig()
    plt.close(fig)

pdf.close()

Strangely:

verticalalignment='bottom'

only shifts the suptitle higher (and off the top of the page slightly), which makes me think that it is aligning itself off different boundaries than the edges of the page?

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Curious Student
  • 669
  • 4
  • 13
  • 25

1 Answers1

18

From https://matplotlib.org/devdocs/api/_as_gen/matplotlib.pyplot.suptitle.html:

Add a centered title to the figure.

kwargs are matplotlib.text.Text properties. Using figure coordinates, the defaults are:

x : 0.5

   The x location of the text in figure coords

y : 0.98

   The y location of the text in figure coords

You can move the position of the suptitle in figure coordinates by choosing different values for x and y. For example,

plt.suptitle(country, x=0.1, y=.95, horizontalalignment='left', verticalalignment='top', fontsize = 15)

will put the suptitle in the upper left corner.

The keywords horizontalalignment and verticalalignment work a bit different ( see e.g. https://matplotlib.org/users/text_props.html):

horizontalalignment controls whether the x positional argument for the text indicates the left, center or right side of the text bounding box.

verticalalignment controls whether the y positional argument for the text indicates the bottom, center or top side of the text bounding box.

jdamp
  • 1,379
  • 1
  • 15
  • 22
  • 3
    Thank you - this is working. So I guess I have understood the original parameters incorrectly - ha and va will do the alignments given the coordinates the suptitle is in, but x, and y are needed to actually set the general position on the layout? – Curious Student Oct 26 '17 at 11:36
  • 1
    Yes, exactly. I added some more detail about those keywords in the answer. – jdamp Oct 26 '17 at 11:38
  • 1
    The original docs on this seem to make it a point to obscure all of these usage details – matanster Aug 29 '18 at 07:22