【问题标题】:Insert an svg image in matplotlib figure在 matplotlib 图中插入 svg 图像
【发布时间】:2021-06-06 22:29:00
【问题描述】:

这是我之前帖子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, 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 扩展名中的相同图像(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, 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.x matplotlib svg figure insets


【解决方案1】:

基于this answer,您可以使用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()

【讨论】:

  • 感谢您的回复。我运行了上面发布的代码。不幸的是,我收到以下错误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
  • 我建议你尝试安装cairosvg with conda: conda install cairosvg -c conda-forge
猜你喜欢
  • 2014-11-19
  • 1970-01-01
  • 2022-01-04
  • 2020-09-16
  • 2020-05-05
  • 2012-08-23
  • 2015-10-05
  • 2023-04-05
  • 2022-11-07
相关资源
最近更新 更多