41

I have two plots

import matplotlib.pyplot as plt
plt.subplot(121)
plt.subplot(122)

I want plt.subplot(122) to be half as wide as plt.subplot(121). Is there a straightforward way to set the height and width parameters for a subplot?

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
thenickname
  • 6,684
  • 14
  • 41
  • 42
  • 1
    Possible duplicate of [Matplotlib different size subplots](http://stackoverflow.com/questions/10388462/matplotlib-different-size-subplots) – Vincenzooo Feb 16 '17 at 22:12

3 Answers3

54

See the grid-spec tutorial:

http://matplotlib.sourceforge.net/users/gridspec.html

Example code:

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

f = plt.figure()

gs = gridspec.GridSpec(1, 2,width_ratios=[2,1])
              
ax1 = plt.subplot(gs[0])
ax2 = plt.subplot(gs[1])

plt.show()

enter image description here

You can also adjust the height ratio using a similar option in GridSpec

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
JoshAdel
  • 66,734
  • 27
  • 141
  • 140
  • Thanks for the tip. I don't have access to import matplotlib.gridspec as gridspec. Is there another way? – thenickname Feb 22 '11 at 21:24
  • Is the issue that you're using an older version of matplotlib that doesn't support GridSpec? It's unclear in your question. – JoshAdel Feb 22 '11 at 22:45
  • @thenickname : you can do `import matplotlib` and call `matplotlib.gridspac.GridSpec(1, 2, etc.)` – heltonbiker Dec 07 '11 at 12:25
  • 1
    Is there a way to specify the size of a subplot/grid column in absolute terms? ie: To draw a custom colorbar with a fixed width? – drevicko Jul 02 '13 at 00:07
21

Yes, and if you want to reduce your code to a single line, you can put all kwargs that are to be passed to matplotlib.gridspec.GridSpec(), into the gridspec_kw parameter of plt.subplots():

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

fig, axs = plt.subplots(nrows=2, ncols=2, gridspec_kw={'width_ratios':[2,1], 'height_ratios':[2,1]})

df = pd.DataFrame(np.random.randn(10, 3), columns=['A', 'B', 'C'])
df.plot.bar(ax=axs[0][0])
df.boxplot(ax=axs[0][1])
df.plot.line(ax=axs[1][0])
df.plot.kde(ax=axs[1][1])

enter image description here

xuancong84
  • 1,412
  • 16
  • 17
14

By simply specifying the geometry with “122”, you're implicitly getting the automatic, equal-sized columns-and-rows layout.

To customise the layout grid, you need to get a little more specific. See “Customizing Location of Subplot Using GridSpec” in the Matplotlib docs.

bignose
  • 30,281
  • 14
  • 77
  • 110