7

I have created a figure and have attached to it a title like this:

def func():
    fig = plt.figure()
    fig.suptitle("my title")
    return fig

Now I would like to retrieve the title I set in the function. Something like this:

fig.get_title()

It seems not to exist. Any idea besides returning the Text object that I can get from the fig.suptitle("w/e") function ?

Xema
  • 1,796
  • 1
  • 19
  • 28

3 Answers3

14

There seems to be no public API to access this. But with some cautions you could use the non-public / potentially instable members:

fig._suptitle.get_text()
languitar
  • 6,554
  • 2
  • 37
  • 62
4

You can get the title through the axes:

fig.axes[0].get_title()

In case you have access to the axis itself, you can directly do:

ax.get_title()

The above is for getting the title associated with an axis e.g, set via plt.title or ax.set_title, i.e. the "usual" title.


But if you are looking for the title of the figure i.e. the suptitle in case it has been set (e.g., for a figure with many subplots), you can write

fig._suptitle.get_text()
Mustafa Aydın
  • 17,645
  • 4
  • 15
  • 38
  • it does not work for: ```fig, ax = plt.subplots(3,2) fig.suptitle('lalala') fig.axes[0].get_title()``` it returns empty string '' – Yarden Cohen May 27 '21 at 11:58
  • @YardenCohen Yes, in case of multiple axes, things are a bit different because there are many possible titles! In your case, there could be 6 titles. But `suptitle` is above all of them, so to get that you can do: `fig._suptitle.get_text()`. – Mustafa Aydın May 27 '21 at 12:03
  • ...and the empty string it returns is the top left sub-figure's title, which is indeed not set and empty. – Mustafa Aydın May 27 '21 at 12:04
  • forgive me if I'm mistaken but isn't suptitle is ment for subplots? since ax.title() is for specific plot so fig.suptitle() is for the entire figure – Yarden Cohen May 27 '21 at 12:08
  • @YardenCohen Your second sentence seems to answer your question, no? `suptitle` is assocaited with the *figure* whereas the "usual" titles are associated with the *axes*. – Mustafa Aydın May 27 '21 at 12:11
  • I see now your edit, Long story short, there is no public way of reading the figure suptitle.. (As the title of the question) – Yarden Cohen May 29 '21 at 18:46
2

Another solution would be to use fig.texts which returns a list of matplotlib.text.Text objects. Therefore, we can get the first element of the list, then use get_text() to get the actual title:

fig = plt.figure()
fig.suptitle("my title")

text = fig.texts[0].get_text()
print(text)
# my title
DavidG
  • 24,279
  • 14
  • 89
  • 82