Tuesday, February 17, 2009

images side-by-side in mpl

The matplotlib specifies its axes position in the normalized figure coordinate, and this may not be best option for showing images. In the mpl SVN example directory, there are two helper classes I wrote (axes_divider.py, axes_grid.py) which may help in some situations.

ex 1. Images with same size.

import matplotlib.pyplot as plt
from axes_grid import AxesGrid, get_demo_image


F = plt.figure(1, (6, 6))
grid = AxesGrid(F, 111, # similar to subplot(111)
nrows_ncols = (2, 2), # 2x2 grid of images
axes_pad = 0.1, # pad in inches
add_all=True, # add axes to the figure
share_all=True, # x & yaxis of all axes are shared
label_mode = "L",
)

Z, extent = get_demo_image() # demo image

for i in range(4):
ax = grid[i]
im = ax.imshow(Z, extent=extent,
origin="lower", interpolation="nearest")

plt.draw()



ex 2. Images with same height but different width.

The above code can be similarly used in this case.

import matplotlib.pyplot as plt
from axes_grid import AxesGrid, get_demo_image


F = plt.figure(1, (9, 4.5))
grid = AxesGrid(F, 111, # similar to subplot(111)
nrows_ncols = (1, 3),
axes_pad = 0.1,
add_all=True,
label_mode = "L",
)

Z, extent = get_demo_image() # demo image

im_widths = [7, 5, 3] # image widths

for i, w in enumerate(im_widths):
ax = grid[i]
myextent = (extent[0], extent[0]+w, extent[2], extent[3])
im = ax.imshow(Z, extent=myextent, origin="lower", interpolation="nearest")

plt.draw()

No comments:

Followers