Certain classes of Sage objects may provide methods
to return svg or tikz representations as strings.
For plots such as the one in the question though, plotting
and saving are delegated to matplotlib, who produces the
svg string. No direct method provides the svg string.
The obvious workaround is to save to a file, and then read the file into a string.
To illustrate, define a function and plot the corresponding slope field:
sage: f = lambda x, y: sin(x + y) + cos(x + y)
sage: p = plot_slope_field(f, (-3, 3), (-3, 3))
Save the plot into a file (see note at the end of this answer):
sage: filename = 'slope_field.svg'
sage: p.save(filename)
Read the saved file:
sage: with open(filename, 'r') as f:
....: s = f.read()
Check the result by printing an initial and a final fragment:
sage: print(s[:155], "...", s[-30:], sep='\n')
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
...
</clipPath>
</defs>
</svg>
Note: to create the file as a temporary file that will get cleaned up automatically when Sage exits:
sage: filename = tmp_filename(ext='.svg')
It is of course also possible to delete the file oneself, without waiting for Sage to exit:
sage: os.remove(filename)
The real engine behind this is matplotlib's "savefig" function. It explicitly also allows a "file-like" object (in which case the "file" format must be specified explicitly, because there's no file name extension to infer it from). With that, you'd be able to write to a StringIO object. Probably using a temporary file is easier, though, and it might be the case that the wrapping that sage has done loses the ability to use a file-like object rather than a file name.
It's a shame that there's no (optional) keyword argument in Sage ala
.save('foo.xml',file_format='svg')
that lets you explicitly ask for a desired file format.It would be totally doable to implement that. Sage plotting (at least the 2d stuff) is all wrapping matplotlib, so whatever is available there can be exposed fairly straightforwardly in sage as well. It just needs someone willing and able to do the job.