Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 273
Richard Avatar asked Dec 01 '15 19:12

Richard


People also ask

How do you change the figure size in a subplot?

To change figure size of more subplots you can use plt. subplots(2,2,figsize=(10,10)) when creating subplots.

How do I change the width and height of a Matplotlib?

Set the Height and Width of a Figure in Matplotlib Instead of the figsize argument, we can also set the height and width of a figure. These can be done either via the set() function with the figheight and figwidth argument, or via the set_figheight() and set_figwidth() functions.

How do I change the space between 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.


2 Answers

You can actually specify height and widthplt.savefig('Desktop/test.png',dpi=500) , even though it's not listed as keyword in the help (I think it is passed on to the figure call(?)):

fig,axs=plt.subplots(nrows,ncols,figsize=(width,height)) 

For some reason, dpi is ignored though. However, you can use it when saving the figure, when it is important:

plt.savefig('test.png',dpi=1000)
like image 149
TNT Avatar answered Oct 07 '22 17:10

TNT


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)

plt.show()

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

Usage:

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-');
like image 36
salomonvh Avatar answered Oct 07 '22 17:10

salomonvh