关于python:将svg文件导入matplotlib图

Importing an svg file into a matplotlib figure

我喜欢制作高质量的绘图,因此尽可能避免使用栅格化的图形。

我正在尝试将svg文件导入到matplotlib图形上:

1
2
3
4
5
import matplotlib.pyplot as plt
earth   = plt.imread('./gfx/earth.svg')
fig, ax = plt.subplots()
im      = ax.imshow(earth)
plt.show()

这与png完美搭配。有人可以告诉我如何使用svg进行操作,或者至少将我指向适当的文档。

我知道有人问过类似的问题(但未回答):这里。此后有什么变化吗?

P.S。我知道我可以导出高分辨率png并达到类似的效果。这不是我要寻找的解决方案。

这是我要导入的图像:

Earth_from_above


也许您正在寻找的是svgutils

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import svgutils.compose as sc
from IPython.display import SVG # /!\\ note the 'SVG' function also in svgutils.compose
import numpy as np

# drawing a random figure on top of your SVG
fig, ax = plt.subplots(1, figsize=(4,4))
ax.plot(np.sin(np.linspace(0,2.*np.pi)), np.cos(np.linspace(0,2.*np.pi)), 'k--', lw=2.)
ax.plot(np.random.randn(20)*.3, np.random.randn(20)*.3, 'ro', label='random sampling')
ax.legend()
ax2 = plt.axes([.2, .2, .2, .2])
ax2.bar([0,1], [70,30])
plt.xticks([0.5,1.5], ['water  ', ' ground'])
plt.yticks([0,50])
plt.title('ratio (%)')
fig.savefig('cover.svg', transparent=True)
# here starts the assembling using svgutils
sc.Figure("8cm","8cm",
    sc.Panel(sc.SVG("./Worldmap_northern.svg").scale(0.405).move(36,29)),
    sc.Panel(sc.SVG("cover.svg"))
    ).save("compose.svg")
SVG('compose.svg')

输出:

enter image description here


SVG(可缩放矢量图形)是一种矢量格式,这意味着图像不是由像素组成,而是由可以任意缩放的相对路径组成。

NumPy / Matplotlib,作为数字软件,只能真正用于像素图形,不能处理svg。我建议先将svg文件转换为通过打开并将png文件保存在Inkscape(免费)等软件中。然后,在Python中打开导出的png

或者,使用Wikimedia提供的图片信息页面上png格式的文件版本(单击图片右侧的下载按钮)。

如果您真的认为您需要矢量形式,那么就没有办法。您总是可以手动将matplotlib图形叠加到图形上(使用matplotlib Artist在图形画布上绘制),或者通过一些pycairo魔术进行保存。但是Matplotlib无法直接使用svg内容。