1

This is a follow-up to my previous post here.

I'm trying to add an SVG image in matplotlib figure as inset.

import matplotlib.pyplot as plt
import numpy as np

from matplotlib.figure import Figure
from matplotlib.offsetbox import OffsetImage, AnnotationBbox


ax = plt.subplot(111)
ax.plot(
    [1, 2, 3], [1, 2, 3],
    'go-',
    label='line 1',
    linewidth=2
 )
arr_img = plt.imread("stinkbug.svg")
im = OffsetImage(arr_img)
ab = AnnotationBbox(im, (1, 0), xycoords='axes fraction')
ax.add_artist(ab)
plt.show()

The code works when the input image is in png format. But I am not able to add the same image saved in svg extension(image).

I get the following error

PIL.UnidentifiedImageError: cannot identify image file

EDIT: I tried to read the svg file via svglib

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.figure import Figure
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
from svglib.svglib import svg2rlg

ax = plt.subplot(111)
ax.plot(
    [1, 2, 3], [1, 2, 3],
    'go-',
    label='line 1',
    linewidth=2
 )
# arr_img = plt.imread("stinkbug.svg")
arr_img = svg2rlg("stinkbug.svg")
im = OffsetImage(arr_img)
ab = AnnotationBbox(im, (1, 0), xycoords='axes fraction')
ax.add_artist(ab)
plt.show()

Error:

"float".format(self._A.dtype))
TypeError: Image data of dtype object cannot be converted to float

Could someone please have a look?

Natasha
  • 1,111
  • 5
  • 28
  • 66

1 Answers1

1

Based on this answer, you can use cairosvg to first convert your SVG to PNG, and then add to your figure.

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.figure import Figure
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
from cairosvg import svg2png

ax = plt.subplot(111)
ax.plot(
    [1, 2, 3], [1, 2, 3],
    'go-',
    label='line 1',
    linewidth=2
 )
# arr_img = plt.imread("stinkbug.svg")
svg2png(url="stinkbug.svg",  write_to="stinkbug.png")

arr_img = plt.imread("stinkbug.png")
im = OffsetImage(arr_img)
ab = AnnotationBbox(im, (1, 0), xycoords='axes fraction')
ax.add_artist(ab)
plt.show()
foglerit
  • 7,792
  • 8
  • 44
  • 64
  • Thanks for the response. I ran the code posted above. Unfortunately, I get the following error `raise OSError("dlopen() failed to load a library: %s" % ' / '.join(names)) OSError: dlopen() failed to load a library: cairo / cairo-2 / cairo-gobject-2 / cairo.so.2` – Natasha Mar 09 '21 at 15:32
  • I suggest you try to install `cairosvg` with conda: `conda install cairosvg -c conda-forge` – foglerit Mar 09 '21 at 17:01
  • Is there no way to import the svg object as such and save everything as a vector image? One of the main advantages of matplotlib is that the output is vector image when saved as svg or pdf. – Adriaan Jul 27 '23 at 16:34