How to add a title to subheadings in Matplotlib?

I have one figure that contains many subheadings.

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 to add headings to subheadings?

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

Thank you for your help.

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

+117
python matplotlib plot subtitle
Aug 11 '14 at 9:25
source share
4 answers

ax.set_title() should set the headers for the individual subheadings:

 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 rewrites them later?

+163
Aug 11 '14 at 12:15
source share

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 headings to subheadings

+64
Aug 24 '16 at 21:57
source share

A short answer assuming import matplotlib.pyplot as plt :

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

how in:

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

Then there is no need for extra variables.

+11
Dec 15 '17 at 9:04 on
source share

If you want to make it shorter, you can write:

 import matplolib.pyplot as plt for i in range(4): plt.subplot(2,2,i+1).set_title('Subplot nยฐ{}' .format(i+1)) plt.show() 

This makes it less clear, but you do not need more lines or variables.

+3
Dec 04 '18 at 16:44
source share



All Articles