What is the best way to create a (3,3) subplot matrix in python with the following catch:
The last two subplots should have equal size. This means they will meet in the middle of the middle plot for the other two columns.
I tried to do this with gridspec but did not managed so far.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import gridspec
# generate some data
x = np.arange(0, 10, 0.2)
y = np.sin(x)
# plot it
fig = plt.figure(figsize=(8, 6))
gs = gridspec.GridSpec(3, 3)
ax0 = plt.subplot(gs[0])
ax0.plot(x, y)
ax1 = plt.subplot(gs[1])
ax1.plot(y, x)
ax3 = plt.subplot(gs[3])
ax3.plot(y, x)
ax4 = plt.subplot(gs[4])
ax4.plot(y, x)
ax6 = plt.subplot(gs[6])
ax6.plot(y, x)
ax7 = plt.subplot(gs[7])
ax7.plot(y, x)
plt.tight_layout()
plt.savefig('grid_figure.png')
plt.show()
The subplot() Function The layout is organized in rows and columns, which are represented by the first and second argument. The third argument represents the index of the current plot. plt.subplot(1, 2, 1) #the figure has 1 row, 2 columns, and this plot is the first plot.
To change figure size of more subplots you can use plt. subplots(2,2,figsize=(10,10)) when creating subplots.
We can use the plt. subplots_adjust() method to change the space between Matplotlib subplots. The parameters wspace and hspace specify the space reserved between Matplotlib subplots. They are the fractions of axis width and height, respectively.
Provided answer as answer from the question. The following was written by OP:
Thanks @datasailor for the solution. Here is a working example:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import gridspec
# generate some data
x = np.arange(0, 10, 0.2)
y = np.sin(x)
# plot it
fig = plt.figure(figsize=(8, 6))
gs = gridspec.GridSpec(6, 3)
ax0 = plt.subplot(gs[0:2,0])
ax0.plot(x, y)
ax1 = plt.subplot(gs[2:4,0])
ax1.plot(y, x)
ax2 = plt.subplot(gs[4:6,0])
ax2.plot(y, x)
ax3 = plt.subplot(gs[0:2,1])
ax3.plot(x, y)
ax4 = plt.subplot(gs[2:4,1])
ax4.plot(y, x)
ax5 = plt.subplot(gs[4:6,1])
ax5.plot(y, x)
ax6 = plt.subplot(gs[0:3,2])
ax6.plot(x, y)
ax7 = plt.subplot(gs[3:6,2])
ax7.plot(y, x)
plt.tight_layout()
plt.savefig('grid_figure.png')
plt.show()
No need to use gridspec here. Just add the subplots where you want to have them.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import gridspec
# generate some data
x = np.arange(0, 10, 0.2)
y = np.sin(x)
# plot it
fig = plt.figure(figsize=(8, 6))
ax1= fig.add_subplot(3,3,1)
ax2= fig.add_subplot(3,3,2)
ax3= fig.add_subplot(3,3,4)
ax4= fig.add_subplot(3,3,5)
ax5= fig.add_subplot(3,3,7)
ax6= fig.add_subplot(3,3,8)
ax7= fig.add_subplot(2,3,3)
ax8= fig.add_subplot(2,3,6)
plt.show()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With