Reputation: 10359
I'm trying to use both ax.set_title()
and plt.suptitle()
to incorporate a title and a subtitle to a graph, but the two seem to not share the same alignment. For example, the following:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
cats = ('One', 'Two')
vals = (12, 4)
ax.barh(cats, vals, align='center')
plt.suptitle('Title')
ax.set_title('Title')
plt.show()
Gives us the following misaligned titles:
How can I get these two titles to align properly? I thought it may be something to do with ax.title
aligning to the axis and plt.suptitle
aligning to the figure, but testing a much longer y label doesn't seem to affect the offset:
fig, ax = plt.subplots()
cats = ('One million tiny engines running at one hundred miles per hour', 'Two')
vals = (12, 4)
ax.barh(cats, vals, align='center')
plt.suptitle('Title')
ax.set_title('Title')
plt.show()
Upvotes: 5
Views: 8322
Reputation: 5913
If you really don't need subtitle
fig, ax = plt.subplots()
cats = ('One million tiny engines running at one hundred miles per hour', 'Two')
vals = (12, 4)
ax.barh(cats, vals, align='center')
ax.set_title('Title\nTitle')
plt.show()
Upvotes: 0
Reputation: 629
matplotlib aligns suptitle to the figure, and title to the subplot. You can manually jiggle the suptitle using fig.subplotpars
:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
cats = ('One', 'Two')
vals = (12, 4)
# Mid point of left and right x-positions
mid = (fig.subplotpars.right + fig.subplotpars.left)/2
ax.barh(cats, vals, align='center')
plt.suptitle('Title',x=mid)
ax.set_title('Title')
plt.show()
Enjoy!
Upvotes: 14
Reputation: 434
I know this isn't the perfect answer and basically a repost of my comment, but here goes nothing:
fig, ax = plt.subplots()
cats = ('hour', 'Two')
vals = (12, 4)
ax.barh(cats, vals, align='center')
plt.figtext(.5,.95,'Foo Bar', fontsize=18, ha='center')
plt.figtext(.5,.9,'lol bottom text',fontsize=10,ha='center')
plt.show()
You need to manually adjust the .95 and .9 values depending on the font sizes though.
Upvotes: 3