Take the 2-minute tour ×

I'm trying to make a figure that's a gird of plots within a grid of plots in matplotlib. I'm using matplotlib 1.1.1 and python 2.7.4.

I following the example on this page of documentation: http://matplotlib.org/users/gridspec.html#a-complex-nested-gridspec-using-subplotspec

fig = plt.figure(figsize=(11, 10))
levels2=[2,8,32,64,128, 256, 512]

def plotcmd(ax, x, y, bins, levels):

    h, xe, ye = np.histogram2d(x, y, bins=70)
    cont = ax.contourf(h.T, extent=[xe[0],xe[-1], ye[0],ye[-1]], levels=levels,
        zorder=2, cmap=cmap)
    cont = ax.contour(h.T, extent=[xe[0],xe[-1], ye[0],ye[-1]], levels=levels, zorder=3,
        colors=('black', 'black', 'black','black'))
    # set limits
    plt.xlim(-1, 5)
    plt.ylim(13, 2)

for i in xrange(4):
    inner_grid = gridspec.GridSpecFromSubplotSpec(1, 3,
        subplot_spec=outer_grid[i], wspace=0.0, hspace=0.0)
    for j in xrange(3):
        ax = plt.Subplot(fig, inner_grid[j])
        plotcmd(ax, data1[:,0]-data1[:,1], data1[:,1], bins, levels2)

So this should create a figure that has four outer panels each hosting three inner panels. It is nearly correct but there are two issues with the final plot:

1.) The final plot, so when i == 3 and j == 2, does not adhere to the limits that I'm setting in plotcmd, it's as if they didn't exist

2.) Underneath the four big panels a figure is being plotted.

I don't understand why, if all indications are that I'm iterating through the outer and inner grids correctly the x- and y- limits wouldn't affect the final plot.

Thanks for any help.


share|improve this question
1) 1.1 is a very old version and the docs are written against newer versions, please try your code on 1.3 2) failing that, please reduce this to the minimum amount of code needed to replicate the problem. –  tcaswell Apr 2 at 12:30

1 Answer 1

As tcaswell suggested I upgraded my version of matplotlib to 1.3.2 however that did not solve the gridspec problem but I was able to get it working as I wanted it to.

I don't necessarily understand why my previous code had the effect that it did but once I changed my plotcmd function to look like this:

def plotcmd(x, y, bins, levels, ax):
    h, xe, ye = np.histogram2d(x, y, bins=bins)
                        levels=levels, zorder=2, cmap=cmap)
                       levels=levels, colors=('black', 'black', 'black','black'))
    ax.set_xlim(-1, 5)
    ax.set_ylim(13, 2)

the resulting plot looks fine.

share|improve this answer

Your Answer


