How to make an axes occupy multiple subplots with pyplot (Python)


Question

I would like to have three plots in single figure. The figure should have a subplot layout of two by two, where the first plot should occupy the first two subplot cells (i.e. the whole first row of plot cells) and the other plots should be positioned underneath the first one in cells 3 and 4. I know that matlab allows this by using the subplot command like so

subplot(2,2,[1,2]) % the plot will span subplots 1 and 2

Is it also possible in pyplot to have a single axes occupy more than one subplot? The docstring of pyplot.subplot doesn't talk about it.

Anyone got an easy solution? Thanks in advance

1
33
5/29/2015 4:00:37 AM

Accepted Answer

You can simply do:

x = numpy.arange(0, 7, 0.01)

subplot(2, 1, 1)
plot(x, sin(x))

subplot(2, 2, 3)
plot(x, cos(x))

subplot(2, 2, 4)
plot(x, sin(x)*cos(x))

i.e., the first plot is really a plot in the upper half (the figure is only divided into 2*1 = 2 cells), and the following two smaller plots are done in a 2*2=4 cell grid. The third argument to subplot() is the positon of the plot inside the grid: for example in the second subplot (subplot(2, 2, 3)), the axes will go to the third section of the 2*2 matrix i.e, to the bottom-left corner.

44
5/29/2015 4:01:53 AM

To have multiple subplots with an axis occupy, you can simply do:

from matplotlib import pyplot as plt
import numpy as np

b=np.linspace(-np.pi, np.pi, 100)

a1=np.sin(b)

a2=np.cos(b)

a3=a1*a2

plt.subplot(221)
plt.plot(b, a1)
plt.title('sin(x)')

plt.subplot(222)
plt.plot(b, a2)
plt.title('cos(x)')

plt.subplot(212)
plt.plot(b, a3)
plt.title('sin(x)*cos(x)')

plt.show()

enter image description here

Another way is

plt.subplot(222)
plt.plot(b, a1)
plt.title('sin(x)')

plt.subplot(224)
plt.plot(b, a2)
plt.title('cos(x)')

plt.subplot(121)
plt.plot(b, a3)
plt.title('sin(x)*cos(x)')

plt.show()

enter image description here


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon