Bertrand Caron
Bertrand Caron

Reputation: 2657

Matplotlib: Embedding images in several subplots()

I'd like to generate a multi-plot with matplotlib and embed an image in the corner of each of my subplot.

I have been able to embed an image in a (single) plot figure using the following example of the matplotlib documentation (code provided below).

I am now trying to embed an image in the corner of each of a series of subplots. I can't seem to find a function similar to the figure's add_axes() on which my previous example relied.

How could I achieve the desired layout ?

import pylab as plt
from numpy import linspace
from matplotlib.cbook import get_sample_data
from scipy.misc import imread

xs = linspace(0, 1, 100)

def single_plot():
    fig, ax = plt.subplots()
    ax.plot(xs, xs**2)

    fn = get_sample_data("grace_hopper.png", asfileobj=False)
    image_axis = fig.add_axes([0.65, 0.70, 0.3, 0.2], anchor='NE', zorder=10)
    image_axis.imshow(imread(fn))

    plt.show()
    plt.clf()

def multi_plot():
    fig, axes = plt.subplots(4)
    for axis in axes:
        axis.plot(xs, xs**2)
        # How to draw the same image as before in the corner of each subplot ?
    plt.show()

if __name__ == '__main__':
    single_plot()
    multi_plot()

Upvotes: 1

Views: 1218

Answers (1)

Brian
Brian

Reputation: 468

You can use the same methods to overlay an image on multiple subplots. The axis position must be defined for each image you want to overlay relative to the figure as a whole. Here is a simple example using your code and the Matplotlib documentation.

def multi_plot():
    fig, axes = plt.subplots(4, 1, figsize=(8, 10))
    fn = get_sample_data("grace_hopper.png", asfileobj=False)
    image = plt.imread(fn)
    x = 0
    for axis in axes:
        axis.plot(xs, xs**2)

        # [left, bottom, width, height]
        image_axis = fig.add_axes([0.125, 0.25 + x, 0.15, 0.65], 
                              zorder=10, anchor="N")
        image_axis.imshow(image)
        image_axis.axis('off')
        x -= 0.209

    plt.show()

I've chosen to incrementally decrease the position of the new axis relative to the bottom of the figure. You could also specify an exact position for each image overlay you want to add.

The above code yields a plot that looks like this: Image Overlay Subplots

Upvotes: 4

Related Questions