yamixpcool
yamixpcool

Reputation: 111

How to add title to subplots with loop?

I am trying to create a plot with 9 subplots and create titles to them using for loop to avoid having to specify the title 9 times. However, my codes work for the first 8 subplots but not the last plot. Please help.

from scipy.stats import beta
import matplotlib.pyplot as plt
import numpy as np

a=[1,10,20,30,40,50,60,70,80,90]
b=[1,10,20,30,40,50,60,70,80,90]

x = np.linspace(0.001,0.999, num=100)

for i in range(9):
    plt.title('alpha=' + str(a[i])+' beta= ' + str(b[i]))
    plt.subplot(3, 3, i+1)
    plt.plot(x, beta.pdf(x, a[i], b[i]),'r-', lw=3, alpha=0.6, label='beta pdf')
    plt.xticks(np.arange(0, 1.5, 0.5))
    plt.yticks(np.arange(0, 13, 6.0))
    plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=0.4)
plt.show()

The resulting plot

Upvotes: 4

Views: 7832

Answers (1)

Mark
Mark

Reputation: 366

just change the order, i.e. plt.title() after plt.subplot(). You got one title less than expected, because your code plotted the title before it has a place to plot.

Also, you can change the size of the plot by plt.figure(figsize=(12,12)) so the subplots don't overlap.

The modified code:

from scipy.stats import beta
import matplotlib.pyplot as plt
import numpy as np

a=[1,10,20,30,40,50,60,70,80,90]
b=[1,10,20,30,40,50,60,70,80,90]

x = np.linspace(0.001,0.999, num=100)

plt.figure(figsize=(12,12))  # change the size of figure!
for i in range(9):
    plt.subplot(3, 3, i+1)
    plt.plot(x, beta.pdf(x, a[i], b[i]),'r-', lw=3, alpha=0.6, label='beta pdf')
    plt.xticks(np.arange(0, 1.5, 0.5))
    plt.yticks(np.arange(0, 13, 6.0))
    plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=0.4)
    plt.title('alpha=' + str(a[i])+' beta= ' + str(b[i]))  # Plot title here!!!
plt.show()

The result is: enter image description here

Upvotes: 2

Related Questions