Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add title to subplots in Matplotlib

I have one figure which contains many subplots.

fig = plt.figure(num=None, figsize=(26, 12), dpi=80, facecolor='w', edgecolor='k')
fig.canvas.set_window_title('Window Title')

# Returns the Axes instance
ax = fig.add_subplot(311) 
ax2 = fig.add_subplot(312) 
ax3 = fig.add_subplot(313) 

How do I add titles to the subplots?

fig.suptitle adds a title to all graphs and although ax.set_title() exists, the latter does not add any title to my subplots.

Thank you for your help.

Edit: Corrected typo about set_title(). Thanks Rutger Kassies

like image 673
Shailen Avatar asked Aug 11 '14 09:08

Shailen


People also ask

How do you add a title to a subplot?

If you use Matlab-like style in the interactive plotting, then you could use plt. gca() to get the reference of the current axes of the subplot and combine title. set_text() method to set title to the subplots in Matplotlib.

Which method is used to add title to the subplots using Matplotlib Mcq?

You can also specify the title of each plot using the set_title() method of each axis.


3 Answers

ax.title.set_text('My Plot Title') seems to work too.

fig = plt.figure()
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(223)
ax4 = fig.add_subplot(224)
ax1.title.set_text('First Plot')
ax2.title.set_text('Second Plot')
ax3.title.set_text('Third Plot')
ax4.title.set_text('Fourth Plot')
plt.show()

matplotlib add titles on subplots

like image 110
Jarad Avatar answered Oct 20 '22 18:10

Jarad


ax.set_title() should set the titles for separate subplots:

import matplotlib.pyplot as plt

if __name__ == "__main__":
    data = [1, 2, 3, 4, 5]

    fig = plt.figure()
    fig.suptitle("Title for whole figure", fontsize=16)
    ax = plt.subplot("211")
    ax.set_title("Title for first plot")
    ax.plot(data)

    ax = plt.subplot("212")
    ax.set_title("Title for second plot")
    ax.plot(data)

    plt.show()

Can you check if this code works for you? Maybe something overwrites them later?

like image 29
masteusz Avatar answered Oct 20 '22 17:10

masteusz


A shorthand answer assuming import matplotlib.pyplot as plt:

plt.gca().set_title('title')

as in:

plt.subplot(221)
plt.gca().set_title('title')
plt.subplot(222)
etc...

Then there is no need for superfluous variables.

like image 58
JMDE Avatar answered Oct 20 '22 17:10

JMDE