Suptitle alignment issues

20.3k Views Asked by At

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?

1

There are 1 best solutions below

3
jdamp On BEST ANSWER

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.