Python 3.x 在matplotlib图中插入svg图像

Python 3.x 在matplotlib图中插入svg图像,python-3.x,matplotlib,svg,figure,insets,Python 3.x,Matplotlib,Svg,Figure,Insets,这是我上一篇文章的后续文章 我试图在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, 2, 3

这是我上一篇文章的后续文章

我试图在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, 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()
当输入图像为png格式时,该代码起作用。但我无法添加保存在svg extension()中的相同图像

我得到以下错误

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, 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()
错误:

"float".format(self._A.dtype))
TypeError: Image data of dtype object cannot be converted to float
有人能看一下吗?

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

导入matplotlib.pyplot作为plt
将numpy作为np导入
从matplotlib.figure导入图形
从matplotlib.offsetbox导入OffsetImage、AnnotationBbox
从cairosvg导入svg2png
ax=plt.子批次(111)
斧头图(
[1, 2, 3], [1, 2, 3],
“去——”,
label='line 1',
线宽=2
)
#arr_img=plt.imread(“臭虫.svg”)
svg2png(url=“bundbug.svg”,write_to=“bundbug.png”)
arr_img=plt.imread(“bundbug.png”)
im=偏移图像(arr\u img)
ab=注释BBox(im,(1,0),xycoords='axes分数')
ax.添加艺术家(ab)
plt.show()

这似乎回答了您的问题:@foglerit您能检查一下我的编辑吗?谢谢您的回复。我运行了上面发布的代码。不幸的是,我遇到了以下错误
raise-OSError(“dlopen()未能加载库:%s”%“/”。join(names))OSError:dlopen()未能加载库:cairo/cairo-2/cairo-gobject-2/cairo.2
我建议您尝试使用conda安装
cairosvg
:conda安装cairosvg-c conda forge