4

I am trying to save a python plot as an svg file:

import matplotlib as mpl
mpl.use('svg')
import matplotlib.pyplot as plt
import numpy as np

plt.figure()
x = np.linspace(0,2*np.pi)
y = np.sin(x)
plt.plot(x, y)
plt.xlabel('Phase $\phi$')
plt.ylabel('Signal')
plt.savefig('SineSignal.svg', format = 'svg')

Works so far. But once I open the file in Inkscape, I cannot edit the text anymore. Seems like python saved the text as a graphic instead as text. Because of this I am neither able to change font, fontsize etc. in Inkscape nor to search for text elements in the plots in the PDF file I create with latex.

Another option is to save the plot as PGF (mpl.use('svg') has to be replaced with mpl.use('pgf') in this case):

plt.savefig('SineSignal.pgf')

This way I am still not able to edit font/fontsize, but at least I can search for textelements in the pdf.

Any suggestions? Using TikZ in python is not an option because the features are quite limited and the plots would look different.

Forrest Thumb
  • 401
  • 5
  • 16
  • SVG format is XML based fromat. Specifications can be found here, if you want to do it from scratch yourself: https://www.w3.org/Graphics/SVG/ – Mika72 May 15 '18 at 08:24
  • What does this mean? I am not familiar at all with XML. – Forrest Thumb May 15 '18 at 08:31
  • See tutorial here: https://www.w3schools.com/graphics/svg_intro.asp If you save code between abd tags in .svg file. More detailled in my Answer (soon). – Mika72 May 15 '18 at 08:39

2 Answers2

10

Found an answer. You can use

new_rc_params = {'text.usetex': False,
"svg.fonttype": 'none'
}
mpl.rcParams.update(new_rc_params)

to prevent the svg backend from rendering the text as paths. For more detailed instructions take a look at Is there an efficient way to store 2D plots as a vector graphic in python?.

Kait B
  • 3
  • 3
Forrest Thumb
  • 401
  • 5
  • 16
  • This works very well, also for including SVG Files in Latex and having the Text typesetted. – Simon Apr 25 '19 at 11:17
1

Doing from scratch option

Minimal code for SVG file with red circle; save to circle.svg:

<?xml version="1.0" encoding="utf-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200" viewBox="0 0 200 200">
  <circle id="circle--red" cx="30" cy="30" r="30" fill="#f00"/>
</svg>

You need probably <path> to create sine wave curve within the SVG. https://www.w3schools.com/graphics/svg_path.asp Replace <circle> element in above. For text, use <text>: https://www.w3schools.com/graphics/svg_text.asp

If you want axises, you can generate those yourself, but using Inkscape or other SVG-able graphics editor may help to create prototype for axes.

Mika72
  • 413
  • 2
  • 12
  • I created the SVG file already (using python). It also looks like what I wanted to create, but apparently the text is stored as a graphic instead as text. – Forrest Thumb May 15 '18 at 09:01