Skip to main content

The PreTeXt Guide

Section 21.2 <sageplot>

Sometimes you don’t want to provide an interactive SageMath environment in the middle of your book (or a chunk of code) but you would like to produce a figure to include in your project by using SageMath. The cleanest way to do this his to put the SageMath code right in your PreTeXt project and use the pretext script that we discussed in Section 19.4 to produce the image files required for your chosen output formats. This is accomplished by using <sageplot> with the script. (The pretext script is fully discussed in Chapter 47, but at least see the aside in Section 19.4 about the additional packages that must be installed and configured to use it properly.)
<figure xml:id="fig-sage-cubic">
  <caption>A cubic plotted by SageMath on
  <image xml:id="sageplot-cubic" width="50%">
    <description>A cubic function on the interval

f(x) = (x-1)*(x+1)*(x-2)
plot(f, (x, -3, 2), color='blue', thickness=3)

Listing 21.2.1. <sageplot> to produce a graphic
We need to run the pretext script to actually make the image files required. If you want to make both HTML and PDF via , you’ll need to run it twice. The first command below (again, enter on one line) makes the SVG to use on the web, and the second makes what you need for . There is an all option that can be passed after -f instead of svg or pdf, but that is more likely to raise errors because some source code cannot produce certain output formats. It’s best to stay away from error-producing steps until you’re comfortable with debugging your system.
$ /path/to/mathbook]/script/pretext -c sageplot -f svg -d ./images /path/to/yoursource.ptx
$ /path/to/mathbook]/script/pretext -c sageplot -f pdf -d ./images /path/to/yoursource.ptx
The code in Listing 21.2.1 produces the following output.
A cubic function on the interval [-3,2]
Figure 21.2.2. A cubic plotted by SageMath on \([-3,2]\)