Python/Matplotlib: controlling the aspect ratio in gridspec

matplotlib, python

Solution

You need to set the figure size so you'll get the aspect ratio you want, which is controlled through the `figsize` parameter of `plt.figure`. It's not clear that you actually need `GridSpec` in this example; I would do:

import matplotlib.pyplot as plt

f, axes = plt.subplots(4, 1, figsize=(10, 4))
f.subplots_adjust(hspace=0)

If you do need to use `GridSpec` for a more complicated layout, you can make the figure with `plt.figure` and then pass the grid slices to the `add_subplot` method of the object that is returned.

Problem

I am trying to control the aspect ratio of 4 x 1 grid using GridSpec. I want very wide plots in the horizontal direction, and compact in the vertical direction, but I can't change the aspect ratio predictably (see first pic). All three settings of the 'height_ratios' below are giving me the same aspect ratio (see second pic below): One: ``` gs = gridspec.GridSpec(4, 1, width_ratios=[1], height_ratios=[0.1, 0.1, 0.1, 0.1]) gs.update(wspace = 0, hspace = 0) ax1 = plt.subplot(gs[0]) ax2 = plt.subplot(gs[1]) ax3 = plt.subplot(gs[2]) ax4 = plt.subplot(gs[3]) plt.show() ``` Two: ``` gs = gridspec.GridSpec(4, 1, width_ratios=[1], height_ratios=[1, 1, 1, 1]) ``` Three: ``` gs = gridspec.GridSpec(4, 1, width_ratios=[1], height_ratios=[0.5, 0.5, 0.5, 0.5]) ``` I was able to get elongated plots, like I want, by doing this: ``` ax1.set_aspect(0.1) ax2.set_aspect(0.1) ax3.set_aspect(0.1) ax4.set_aspect(0.1) ``` But this adds space between the subplots, which I don't want, and I removed using hspace = 0. How do I control the aspect ratio without adding space between the subplots? This is what I want, but I can't seem to get it again and I'm not sure why: Instead, all I get is this: This is what I get using ax.set_aspect(0.1), which has the correct aspect ratio, but it introduces space between the plots, which I don't want:

Original source