Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I save the text in python plots editable in svg files?

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.

like image 995
Forrest Thumb Avatar asked Sep 03 '25 03:09

Forrest Thumb


2 Answers

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?.

like image 73
Forrest Thumb Avatar answered Sep 06 '25 00:09

Forrest Thumb


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.

like image 41
Mika72 Avatar answered Sep 06 '25 01:09

Mika72