(The ideas in this post are based on a worksheet by Jason Grout. Thanks Jason!)

Sage 2D plots use the excellent library matplotlib as a backend, which gives us beautiful publication-quality graphics. Sage only exposes a small subset of matplotlib's capabilities, and this subset is generally sufficient in day-to-day work. However, especially if you are preparing a graph for a class or a presentation, you might need to tweak things to get it to look "just right".

I recently had to produce some graphs of trigonometric functions for my calculus class, and the default tick locations and labels are not really well-suited. Here is one example (code and graph):

var('x')
p = plot(2*sin(x+pi/3)+2, (x, -pi/3, 5*pi/3))
p.save('2sinx_pi_3_2_original.png') 

original graph

There is too much numerical information displayed, and a lot of it is just distracting for this function. I would much rather just see some multiples of (say) \pi/2 marked along the x-axis, and a few significant numbers marked along the y-axis. For this we need to access matplotlib directly. Here is the new code, and the resulting graph:

var('x')
p = plot(2*sin(x+pi/3)+2, (x, -pi/3, 5*pi/3))
fig = p.matplotlib(axes_labels=['$x$', '$y$'])
from matplotlib.backends.backend_agg import FigureCanvasAgg
fig.set_canvas(FigureCanvasAgg(fig))
axes = fig.get_axes()[0]
axes.minorticks_off()
axes.set_xticks([float((j-1/3)*pi) for j in range(0,3)])
axes.set_xticklabels(['$-\pi/3$', '$2\pi/3$', '$5\pi/3$'])
axes.set_yticks([float(2), float(4)])
fig.suptitle('$2\,\sin(x+\pi/3)+2$', color='navy')
fig.savefig('2sinx_pi_3_2_matplotlib.png')

tweaked graph