【发布时间】: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
有人可以看看吗?
【问题讨论】:
-
这似乎回答了你的问题:stackoverflow.com/questions/15130670/…
-
@foglerit 你能检查我的编辑吗?
标签: python-3.x matplotlib svg figure insets