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.

ma7642
  • 139
  • 2
  • 12
  • @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. – ma7642 Jun 28 '20 at 11:29
  • 1
    does [this answer](https://stackoverflow.com/a/48643217/6220759) help you? – Josh Friedlander Jun 28 '20 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? – ma7642 Jun 28 '20 at 11:51
  • 1
    Nevermind, I found this thread: https://stackoverflow.com/questions/16276349/resizing-an-image-in-python Thanks a lot!! – ma7642 Jun 28 '20 at 11:53

0 Answers0