在 matplotlib 图形中插入 svg 图像

问题描述

这是我之前的帖子 here 的后续。

我正在尝试在 matplotlib 图中添加一个 SVG 图像作为插图。

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,'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()

代码在输入图像为 png 格式时有效。但我无法添加保存在 svg 扩展名 (image) 中的相同图像。

我收到以下错误

PIL.UnidentifiedImageError: cannot identify image file

编辑: 我试图通过 svglib

读取 svg 文件
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,linewidth=2
 )
# arr_img = plt.imread("stinkbug.svg")
arr_img = svg2rlg("stinkbug.svg")
im = Offsetimage(arr_img)
ab = AnnotationBBox(im,xycoords='axes fraction')
ax.add_artist(ab)
plt.show()

错误

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

有人可以看看吗?

解决方法

基于 this answer,您可以使用 cairosvg 先将您的 SVG 转换为 PNG,然后添加到您的图形中。

auth