Feeds:
Posts

## Saving Plots in Sage(math)

If you plot a function,

sage: p = plot(sin(x), (x, -3, 3), axes_labels=['$x$', '$\\sin(x)$']; p

and want to save it in a given directory (without showing it) as a JPG file, then use

sage: p = plot(sin(x), (x, -3, 3), axes_labels=['$x$', '$\\sin(x)$'];
p.save(filename = '/path/to/your/directory/file.jpg')

NOTE: it is possible to save the plots as PDF, PNG and EPS.

I was interested in plotting a set of functions depending on a discrete parameter $n$, and save them with an useful name, say file-i.jpg for $n=i$, so the solution is,

sage: for n in range(1,4): p = plot(x^n, (x, -4, 4));
p.save(filename = '/path/file-%s.jpg' %(n))

If there are more parameters, i.e. $m, n$, change the last part as follows,

'file-%s-%s.jpg' %(m,n)

I found the above trick extremelly useful! Hope you do too.