How do I put titles on subplots using matplotlib?

asked 2020-12-22 18:44:07 +0100

rhymesayers gravatar image

I am able to put titles on the subplots using Sage's plotting function, but unable to put titles on the subplots using matplotlib. Here is a simplified code of what I am working with:

import matplotlib.pyplot as mpl
#Function defining Legendre Functions of the Second Kind using Bonnet's recursion formula:
def legendre_second(n,x):
   if (n ==0):
       return log((x+1)/(x-1))/2
   elif (n==1):
       return x*legendre_second(0,x) - 1
   elif (n>1): 
       return ((2*n-1)*x*legendre_second(n-1,x) - (n-1)*legendre_second(n-2,x))/n
#Creating a plot list for the first four legendre function of the second kind:
 l = []
 p = plot(legendre_second(0,x), (x, 1,10), title = r'$Q_0$')
 l.append(p)
 p = plot(legendre_second(1,x), (x, 1,10), title = r'$Q_1$')
 l.append(p)
 p = plot(legendre_second(2,x), (x, 1,10),  title = r'$Q_2$')
 l.append(p)
 p = plot(legendre_second(3,x), (x, 1,10),  title = r'$Q_3$')
 l.append(p)

Plotting Using Sage

# Label the plots on the left column
for i in range(0,2,2):
     l[i].axes_labels(["","Value"])

# Label the plots in the last row
l[-2].axes_labels(["x interval ","Value"])
l[-1].axes_labels(["x interval ",""])

gpairs = list(zip(l[::2], l[1::2]))
pic=graphics_array(gpairs)
graphics_array(gpairs).show(frame=True,figsize=[9,7],gridlines=True)

In which I obtain subplots with titles, I would upload picture but it says I need >60 points to upload files

Now on to plotting with matplotlib

fig = mpl.figure(figsize = (15,10))
for i, g in zip(range(1, 5), pic._glist):
     subplot = mpl.subplot(2, 2, i)
     g.matplotlib(figure=fig, sub=subplot, verify=True, axes=True, frame=True,  gridlines='major')

With matplotlib I am able to obtain the subplots with the x and y axis labels, but the titles of each subplot do not transfer over to the figure created by matplotlib. How do I create titles for each individual subplot in matplotlib? Is it also possible to create an overall title for the entire figure? Thanks again for all of your guy's/girl's help. @dsejas

edit retag flag offensive close merge delete

Comments

Hello, @rhymesayers! I noticed that you changed your original question from which this official version is derived; that confused me a little bit. Please, let me know the following: The solution I gave you as a comment in your original version of this question is good enough? Or are you looking for a purely Matplotlib-not-Sage solution?

dsejas gravatar imagedsejas ( 2020-12-23 06:23:37 +0100 )edit

This is an attempt combining Sage code and Matplotlib.

dsejas gravatar imagedsejas ( 2020-12-23 06:45:20 +0100 )edit

Please, let me know if this is what you expected, so I can make it into a full answer. Also, I can provide different (although similar) alternative approaches.

dsejas gravatar imagedsejas ( 2020-12-23 06:46:13 +0100 )edit