python-3.x - 在 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
有人可以看看吗?
解决方案
基于这个答案,您可以使用 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()
推荐阅读
- meteor - 在 Meteor 中构建期间如何访问客户端代码中的环境变量?
- r - 在 R 中围绕 DBI 编写 RefClass 包装器
- python - 如何更改我的 csv 文件中的列和行?
- python - 查找字符串列表中的差异
- bash - 在 Ubuntu 上运行外部工具 - Intellij 作为 sh 文件 - 找不到命令
- ios - iOS 是否支持 NFC ISO 14443-3 Type-B
- node.js - 作为经过身份验证的用户,我可以使用 ArcGIS REST-API“applyEdits”来更新要素层吗?
- javascript - 最快验证器包:如何拥有多个模式和消息
- java - Jackson 在反序列化 POJO 时坚持抛出令人困惑的异常
- delphi - 等到 Class 在 Delphi 中完成它的工作