简体   繁体   中英

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:)

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
lena = misc.lena()
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(lena)
ax.axis('off')  # get rid of the ticks and ticklabels
plt.show()

I used lena 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 lena in the small script above.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM