4

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

1
  • 1
    Switch the order of the plt.title and plt.subplot lines (so that the plt.subplot line is before the plt.title line). Commented Feb 25, 2016 at 21:20

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.