Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing matplotlib subplot size/position after axes creation

Tags:

Is it possible to set the size/position of a matplotlib subplot after the axes are created? I know that I can do:

import matplotlib.pyplot as plt  ax = plt.subplot(111) ax.change_geometry(3,1,1) 

to put the axes on the top row of three. But I want the axes to span the first two rows. I have tried this:

import matplotlib.gridspec as gridspec  ax = plt.subplot(111) gs = gridspec.GridSpec(3,1) ax.set_subplotspec(gs[0:2]) 

but the axes still fill the whole window.

Update for clarity I want to change the position of an existing axes instance rather than set it when it is created. This is because the extent of the axes will be modified each time I add data (plotting data on a map using cartopy). The map may turn out tall and narrow, or short and wide (or something in between). So the decision on the grid layout will happen after the plotting function.

like image 353
RuthC Avatar asked Apr 05 '14 13:04

RuthC


People also ask

How do I resize a subplot in Matplotlib?

To change the size of subplots in Matplotlib, use the plt. subplots() method with the figsize parameter (e.g., figsize=(8,6) ) to specify one size for all subplots — unit in inches — and the gridspec_kw parameter (e.g., gridspec_kw={'width_ratios': [2, 1]} ) to specify individual sizes.

How do I control the size of a subplot in Python?

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

What does PLT subplot 1 2 2 mean?

The subplot() Function #the figure has 1 row, 2 columns, and this plot is the first plot. plt.subplot(1, 2, 2) #the figure has 1 row, 2 columns, and this plot is the second plot.


1 Answers

Thanks to Molly pointing me in the right direction, I have a solution:

import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec  fig = plt.figure()  ax = fig.add_subplot(111)  gs = gridspec.GridSpec(3,1) ax.set_position(gs[0:2].get_position(fig)) ax.set_subplotspec(gs[0:2])              # only necessary if using tight_layout()  fig.add_subplot(gs[2])  fig.tight_layout()                       # not strictly part of the question  plt.show() 
like image 133
RuthC Avatar answered Oct 11 '22 01:10

RuthC