导入一个svg文件matplotlib图

Sas*_*sha 16 svg matplotlib python-imaging-library

我喜欢制作高质量的地块,因此尽可能避免光栅化的图形.

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

import matplotlib.pyplot as plt
earth   = plt.imread('./gfx/earth.svg')
fig, ax = plt.subplots()
im      = ax.imshow(earth)
plt.show()
Run Code Online (Sandbox Code Playgroud)

这与png完美配合.有人可以告诉我如何使用svg或至少指出我的正确文档.

我知道有一个类似的问题已经被问到(但没有回答):这里.从那以后有什么变化吗

PS我知道我可以导出高分辨率的png并实现类似的效果.这不是我要找的解决方案.

这是我要导入的图像:Earth_from_above.

任何提示都表示赞赏.谢谢!

小智 19

也许你正在寻找的是svgutils

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')
Run Code Online (Sandbox Code Playgroud)

输出:

在此输入图像描述


rap*_*ael 9

致 2021 年来到这里的任何人……

我建议看看cairosvg包装
conda install -c conda-forge cairosvgpip3 install cairosvg

https://cairosvg.org/

import cairosvg
import matplotlib.pyplot as plt
from PIL import Image
from io import BytesIO

img_png = cairosvg.svg2png("... the content of the svg file ...")
img = Image.open(BytesIO(img_png))
plt.imshow(img)
Run Code Online (Sandbox Code Playgroud)