Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add subplot to existing figure?

I'm trying to get to grips with matplotlib. I am having difficulty understanding how to add subplots when the grid shape already exists.

So for example if I create a figure with a 2*2 grid of subplots, how can I add a 5th or 6th. i.e. how can I change the geometry to accomodate another subplot. If I do this:

x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)
f, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, sharex=True, sharey=True, facecolor='red', \
dpi = 100, edgecolor = 'red', linewidth = 5.0, frameon = True)
ax1.plot(x, y)
ax1.set_title('Sharing x per column, y per row')
ax2.scatter(x, y)
ax3.scatter(x, 2 * y ** 2 - 1, color='r')
ax4.plot(x, 2 * y ** 2 - 1, color='r')

and then I want to add another subplot below:

f.add_subplot(3, 2, 5)

Then the new subplot overlaps with the fourth one, when I want it positioned below obviously. Do I need to change the geometry? If so, how? Or is it just a position thing?

More generally what is going on with the **kwargs with subplot? If anyone can help me work out how to start using those, that would also be very handy.

like image 216
Woody Pride Avatar asked Nov 11 '22 18:11

Woody Pride


1 Answers

I think your intuition that you should change the geometry of the plot layout is correct. You are starting off by specifying a (2,2) geometry which is 2 rows and 2 columns, so naturally adding a 5th plot by conventional means can cause some issues. There are various ways to work around this, but one of the simpler solutions is just to give yourself a bigger subplot grid by using a third row of plots--using a (3,2) geometry as in my example below:

%pylab inline
import numpy as np
x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)
#probably easiest to add a third row of plots (3,2) at this stage:
f, ((ax1, ax2), (ax3, ax4),(ax5,ax6)) = plt.subplots(3, 2, sharex=True, sharey=True,    facecolor='red', \
dpi = 100, edgecolor = 'red', linewidth = 5.0, frameon = True)
ax1.plot(x, y)
ax1.set_title('Sharing x per column, y per row')
ax2.scatter(x, y)
ax3.scatter(x, 2 * y ** 2 - 1, color='r')
ax4.plot(x, 2 * y ** 2 - 1, color='r')
#now the fifth plot shouldn't clobber one of the others:
ax5.plot(x,y**3,color='g')

enter image description here

If you want the fifth plot to take up the whole bottom row rather than having a blank 6th plot there you can use more advanced options like matplotlib.gridspec described in the gridspec documentation.

like image 175
treddy Avatar answered Dec 06 '22 20:12

treddy