Richard Richard - 2 years ago 157
Python Question

Set height and width of figure created with plt.subplots in matplotlib?

In matplotlib, I know how to set the height and width and DPI of a figure:

fig = plt.figure(figsize=(4, 5), dpi=100)

However, it seems that if I want to create small multiple plots, I can't create a figure like this, I have to use this:

fig, subplots = plt.subplots(nrows=4, ncols=4)

How can I set the height and width and DPI of a figure created with subplots like this?

Answer Source

A working example of the gridspec module:

import matplotlib.pyplot as plt
from matplotlib import gridspec

fig = plt.figure(figsize=(18,18))

gs = gridspec.GridSpec(3, 3)

ax1 = fig.add_subplot(gs[0,:])
ax1.plot([1,2,3,4,5], [10,5,10,5,10], 'r-')

ax2 = fig.add_subplot(gs[1,:-1])
ax2.plot([1,2,3,4], [1,4,9,16], 'k-')

ax3 = fig.add_subplot(gs[1:, 2])
ax3.plot([1,2,3,4], [1,10,100,1000], 'b-')

ax4 = fig.add_subplot(gs[2,0])
ax4.plot([1,2,3,4], [0,0,1,1], 'g-')

ax5 = fig.add_subplot(gs[2,1])
ax5.plot([1,2,3,4], [1,0,0,1], 'c-')

gs.update(wspace=0.5, hspace=0.5)

But I prefer wrapping it in a function and using it like this:

def mySubplotFunction(fig,gs,x,y,c,ax=None):

    if not ax:
        ax = fig.add_subplot(gs)
    ax.plot(x, y, c)

    return fig, ax


fig2 = plt.figure(figsize=(9,9))
fig2, ax1 = mySubplotFunction(fig2,gs[0,:],[1,2,3,4,5],[10,5,10,5,10],'r-');
fig2, ax2 = mySubplotFunction(fig2,gs[1,:-1],[1,2,3,4],[1,4,9,16],'k-');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download