在matplotlib图中插入svg图像 [英] Insert an svg image in matplotlib figure

查看:140
本文介绍了在matplotlib图中插入svg图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我上一篇帖子的后续文章此处.

This is a follow-up to my previous post here.

我正在尝试在matplotlib图中添加SVG图像作为插图.

I'm trying to add an SVG image in matplotlib figure as inset.

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扩展名中的同一张图片(图片).

The code works when the input image is in png format. But I am not able to add the same image saved in svg extension(image).

我收到以下错误

PIL.UnidentifiedImageError: cannot identify image file

我试图通过svglib读取svg文件

I tried to read the svg file via svglib

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,然后添加到图形中.

Based on this answer, you can use cairosvg to first convert your SVG to PNG, and then add to your figure.

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

这篇关于在matplotlib图中插入svg图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆