Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib: Getting subplots to fill figure

I would please like suggestions for how to override the default matplotlib behaviour when plotting images as subplots, whereby the subplot sizes don't seem to match the figure size. I would like to set my figure size (e.g. to match the width of an A4 page) and have the subplots automatically stretch to fill the space available. In the following example, the code below gives a figure with a lot of white space between the panels:

import numpy as np
import matplotlib.pyplot as plt

data=np.random.rand(10,4)

#creating a wide figure with 2 subplots in 1 row
fig,ax=plt.subplots(1,2, figsize=(9,3))  
ax=ax.reshape(1,len(ax))

for i in [0,1]:
    plt.sca(ax[0,i])
    plt.imshow(data,interpolation='nearest')
    plt.colorbar()

I would like the subplots to be stretched horizontally so that they fill the figure space. I will make many similar plots with different numbers of values along each axis, and the space between the plots appears to depend on the ratio of x values to y values, so I would please like to know if there is a good general way to set the subplot widths to fill the space. Can the physical size of subplots be specified somehow? I've been searching for solutions for a few hours, so thanks in advance for any help you can give.

like image 418
PeterW Avatar asked Jul 02 '14 15:07

PeterW


People also ask

How to add subplot to a figure in Matplotlib?

Add Subplot to a Figure in Matplotlib 1 Add Subplot to a Figure Using the Matplotlib.figure.Figure.add_subplot () Method 2 Create Figure With Subplots Using Matplotlib.pyplot.subplots () More ...

What is the first subplot method in MATLAB?

The first subplot method is given number 221. the first 2 shows rows, and the second 2 shows columns. The figure is divided into a 2X2 matrix. I.e., we have four divisions in the figure.

How to add subplots to a fig in Python?

Here, fig.add_subplot (1,1,1) will add a subplot at first position to the 1 X 1 grid in the figure. Alternatively, we can also use fig.add_subplot (111) to achieve the same result. The add_subplot () method returns a axes object, which can be used to plot and add details to the subplot added. Here, we have a figure with three subplots.

How to control the default spacing of the subplots in Matplotlib?

This module is used to control the default spacing of the subplots and top level container for all plot elements. The subplots () method figure module of matplotlib library is used to display the figure window. Syntax: subplots (self, nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None)


2 Answers

You can adjust your axis area by using the ax.set_position method. It works with relative coordinates, so if you want to make an A4 image, then:

import numpy as np
import matplotlib.pyplot as plt

# figsize keyword talks some obscure units which need a conversion from standard units
plt.figure(figsize=np.array([210,297]) / 25.4)

x = np.linspace(0,2*np.pi, 100)
plt.plot(x, np.sin(x))

plt.gca().set_position([0, 0, 1, 1])

plt.show()

Now the axis area (plot area) fills the whole page.

The coordinates given to the set_position are relative coordinates [left, lower, width, height], where each direction is scaled by the page size.

As pointed out in the other answers, imshow and matshow try sometimes to keep the pixels in the picture square. There is a rather special interplay with the axis ratio and imshow.

  • if imshow is called without extent=[...] or aspect='auto' keyword arguments, it does what is instructed in the local defaults, usually tries to keep the pixels square
  • if this happens (or aspect='equal' is set), the axes act as if plt.axis('scaled') had been called, i.e. keeps X and Y coordinates equal length (pixels per unit) and change the axis size to match the extents
  • this can be overridden by setting plt.axis('tight') (which makes the x and y limits to fit the image exactly)

Th old trick is to use axis('auto') or axis('normal'), but these are nowadays deprecated (use scaled, equal, or tight).

Yes, it is a bit of a mess.

like image 164
DrV Avatar answered Sep 25 '22 23:09

DrV


First, you're using calls to plt when you have Axes objects as your disposal. That road leads to pain. Second, imshow sets the aspect ratio of the axes scales to 1. That's why the axes are so narrow. Knowing all that, your example becomes:

import numpy as np
import matplotlib.pyplot as plt

data = np.random.rand(10,4)

#creating a wide figure with 2 subplots in 1 row
fig, axes = plt.subplots(1, 2, figsize=(9,3))  

for ax in axes.flatten():  # flatten in case you have a second row at some point
    img = ax.imshow(data, interpolation='nearest')
    ax.set_aspect('auto')

plt.colorbar(img)

On my system, that looks like this: enter image description here

like image 24
Paul H Avatar answered Sep 22 '22 23:09

Paul H