user3926620
user3926620

Reputation:

Putting a small image on the corner of a plot with matplotlib

This question lend code from Joe Kington(how to insert a small image on the corner of a plot with matplotlib?):

import matplotlib.pyplot as plt
import Image
import numpy as np

im = Image.open('/home/jofer/logo.png')
height = im.size[1]

# We need a float array between 0-1, rather than
# a uint8 array between 0-255
im = np.array(im).astype(np.float) / 255

fig = plt.figure()

plt.plot(np.arange(10), 4 * np.arange(10))

# With newer (1.0) versions of matplotlib, you can 
# use the "zorder" kwarg to make the image overlay
# the plot, rather than hide behind it... (e.g. zorder=10)
fig.figimage(im, 0, fig.bbox.ymax - height)

# (Saving with the same dpi as the screen default to
#  avoid displacing the logo image)
fig.savefig('/home/jofer/temp.png', dpi=80)

plt.show()

I tried the following:

import matplotlib.pyplot as plt
import Image
import numpy as np

im = Image.open('/home/po/pic.jpg')
height = im.size[1]

im = np.array(im).astype(np.float) / 255

fig = plt.figure()
fig.subplots_adjust(top=0.80)
fig.patch.set_facecolor('black')
ax1 = fig.add_subplot(1, 1, 1, axisbg='white')

fig.figimage(im, 0, fig.bbox.ymax - height)

But my image is at the center rather than at the middle, is there a way to shift it up, i have tried read up on http://effbot.org/imagingbook/image.htm but to no avail

Thanks in advance:)

Upvotes: 3

Views: 7467

Answers (2)

Oliver W.
Oliver W.

Reputation: 13459

I don't see the need for an extra module import when matplotlib has the capabilities to do the same.

If you want to make an inset, simply add (and position) an extra axes object to the figure window. It has some advantages over the figimage method here, because figimage

Adds a non-resampled image to the figure

(matplotlib docs).

Here's an example:

from scipy import misc
face = misc.face()
import matplotlib.pyplot as plt

plt.plot(range(10), range(10))
ax = plt.axes([0.5,0.8, 0.1, 0.1], frameon=True)  # Change the numbers in this array to position your image [left, bottom, width, height])
ax.imshow(face)
ax.axis('off')  # get rid of the ticks and ticklabels
plt.show()

I used face as an image, to make sure anyone can run the code, but you can have matplotlib load your image by typing:

image = plt.imread('/home/po/pic.jpg')

This replaces your call to the Image module, making it obsolete. The variable image serves the same purpose as the variable face in the small script above.

Upvotes: 8

Boris Yakubchik
Boris Yakubchik

Reputation: 4453

Depending on your use-case, it may be far faster and cleaner to just resize the image in your photo editor and then use two lines of code:

    img = image.imread("my_image.png")
    plt.figimage(img, 100, 200, zorder=1, alpha=0.3)

Upvotes: 1

Related Questions