0

I am trying to construct a seaborn plot with a subtitle and using matplotlib's suptitle function to do that. However, the two titles are off-center. They were off-center by default and when I tried manually correcting by setting horizontalalignment='center' with both, nothing changed (which I sort of expected, since I'd read that those are the default values). I can try setting x and y values and trying to eyeball a center placement, but I want it to be exact. I've tried searching stack overflow and GitHub for responses to this issue but haven't found anything. How do I get both the title and the subtitle to center?

minimum viable example:

import seaborn as sns
import matplotlib
from matplotlib import pyplot as plt
import matplotlib.ticker as ticker
import seaborn as sns
%matplotlib inline

sns.set_theme(style="darkgrid")

X = [1,2,3]
y = [.5,.1,.9]

fig, ax = plt.subplots(figsize=(8, 5))  
plt.rcParams['figure.dpi'] = 900

g = sns.scatterplot(x=X, y=y, color='#152238', alpha=0.9, legend = False)

# title
plt.suptitle('This is my Title', fontsize = 18, 
            horizontalalignment='center')
#set the title
plt.title('and this is a subtitle', fontsize = 14, 
            horizontalalignment='center')

enter image description here

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
  • [Related thread](https://stackoverflow.com/questions/1388450/giving-graphs-a-subtitle-in-matplotlib). – BigBen Aug 26 '21 at 20:33
  • 1
    This related thread basically advises people that instead of trying to get title/subtitle to work, to use subtitle/title. Which is functionality already present in my example code. And even the example code in the thread features the lack of alignment that I am asking about. – Non-Contradiction Aug 26 '21 at 21:04
  • 3
    I think `suptitle` is centred on the entire figure, while `title` is centred on the axes. Because of the different whitespace left and right, those two are not necessarily going to be the same. I suppose you could force them to be using something like `fig.subplots_adjust(left=0.1, right=0.9)`, but then you would create unnecessary white space on the right hand side. Alternatively you could use `plt.figtext` instead of `plt.title` and then you can position it anywhere you like (e.g. `plt.figtext(0.5, 0.9, 'and this is a subtitle')`) – tmdavison Aug 26 '21 at 21:07
  • 1
    That's the correct diagnosis @tmdavison. Another suggested hack would be to make the supertitle using `ax.text`, with the text placed outside of the axes limits, so that you can specify its position in axes coordinates, e.g. `ax.text(.5, 1.1, "Super Title", transform=ax.transAxes, ha="center")` – mwaskom Aug 26 '21 at 23:25

0 Answers0