3

I am trying to insert PNG images in a matplotlib figure. Based on answers here and here, this is so far my code:

import matplotlib
import matplotlib.pyplot as plt
import matplotlib.gridspec as gs
from matplotlib.offsetbox import OffsetImage,AnnotationBbox
import seaborn as sns

sns.set_style("white")

image1 = "d1.PNG"
image2 = "d2.PNG"
image3 = "d3.PNG"

img1 = plt.imread(image1)
img2 = plt.imread(image2)
img3 = plt.imread(image3)

fig = plt.figure(tight_layout = True)
gs1 = gs.GridSpec(nrows = 2, ncols = 3)

ax1 = plt.subplot(gs1[:, 1])
ax1.text(x= 0.5, y = 0.5, s = "ax1", va = "center", ha = "center")
ax2 = plt.subplot(gs1[0, 2])
ax2.text(x= 0.5, y = 0.5, s = "ax2", va = "center", ha = "center")
ax3 = plt.subplot(gs1[1, 2])
ax3.text(x= 0.5, y = 0.5, s = "ax3", va = "center", ha = "center")

def add_image(img, coord):
    im = OffsetImage(img, zoom = 0.07)
    im.image.axes = ax1
    ab = AnnotationBbox(im, (0.0, coord),  xybox=(-100, 0.0), frameon=False, xycoords='data',  boxcoords="offset points", pad=0.4)
    ax1.add_artist(ab)

add_image(img1, 0.8)
add_image(img2, 0.45)
add_image(img3, 0.1)

sns.despine(ax = ax1, top = False, right = True, bottom = True)
sns.despine(ax = ax2, top = True, right = True)
sns.despine(ax = ax3, top = True, right = True)

plt.savefig("plot.pdf")

This produces:

enter image description here

The PNG images on the left appear pixelled. Is there a way I can insert these images with better quality?

I also have the images in PDF format. Would it be better if I try to transform the PDFs to PNGs and insert them later? According to what I have read, it is not possible to insert PDFs directly in matplotlib.

Thanks!

EDIT: This is what one of the original images look like: enter image description here

I produced them with PowerPoint (might not be the best tool, I admit) and what I did is to make the slide size large (40cm x 20 cm) trying to improve the quality of the PNGs.

4
  • @JoshFriedlander I edited the post to add the PNG of one of the images and show that they are not pixelled. I don't understand the question about add image ; this is the name of a function I created myself, I don't have to import it. Commented Jun 28, 2020 at 11:29
  • 1
    does this answer help you? Commented Jun 28, 2020 at 11:42
  • @JoshFriedlander Yes, it helps! I was misusing the 'zoom' parameters. Now the resolution is perfect, but the image is huge... Is there a way to resize it? Commented Jun 28, 2020 at 11:51
  • 1
    Nevermind, I found this thread: stackoverflow.com/questions/16276349/… Thanks a lot!! Commented Jun 28, 2020 at 11:53

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.