Set location of image in matplotlib

Viewed 1587

I have a list of three images' file names, I want to plot them using matplotlib, the attempt I made is below. I tried to plot them all but they are all plotted to the same location so the final image appears on top.

I want to plot the first at location coordinates (0,0), the second at (100,200) and the third at (200,200). I read the documentation on matplotlib.imshow but cannot find how to set the location of the image using the coordinates.

import matplotlib.pyplot as plt
import matplotlib.image as mpimg

imageList = ["foo.jpg", "bar.jpg", "foobar.jpg"]
coordinatesList = [[0,0],[100,200],[200,200]]

for i in range(3):
    imageFile = imageList[i]
    coordinate = coordinatesList[i]
    img=mpimg.imread(imageFile)
    imgplot = plt.imshow(img)
1 Answers

I see 2 ways to do this:

  1. with matplotlib.transforms:
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import matplotlib as mpl


imageList = ["image.jpg", "image.jpg", "image.jpg"]
coordinatesList = [[0, 0], [100, 200], [200, 200]]

ax = plt.gca()
ax.set_xlim(0, 300)
ax.set_ylim(0, 300)

for i in range(3):
    imageFile = imageList[i]
    img=mpimg.imread(imageFile)
    imgplot = ax.imshow(img)
    tx, ty = coordinatesList[i]
    transform = mpl.transforms.Affine2D().translate(tx, ty)
    imgplot.set_transform(transform + ax.transData)

plt.show()
  1. with extent option (but I know my image's dimensions):
import matplotlib.pyplot as plt
import matplotlib.image as mpimg


imageList = ["image.jpg", "image.jpg", "image.jpg"]
coordinatesList = [[0, 0], [100, 200], [200, 200]]

ax = plt.gca()
ax.set_xlim(0, 300)
ax.set_ylim(0, 300)

imgplot = [None] * len(imageList)
for i in range(3):
    imageFile = imageList[i]
    img=mpimg.imread(imageFile)
    tx, ty = coordinatesList[i]
    ax.imshow(img, extent=(tx, tx + 50, ty, ty + 50))

plt.show()

Here's the result using a 50px square as a picture image.png: enter image description here

Related