首页 > 解决方案 > 在 matplotlib 图中插入 svg 图像

问题描述

这是我之前的帖子的后续内容。

我正在尝试在 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 扩展名(图像)中的相同图像。

我收到以下错误

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

有人可以看看吗?

标签: python-3.xmatplotlibsvgfigureinsets

解决方案


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

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

推荐阅读