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 48, but at least see the aside in Section 19.4 about the additional packages that must be installed and configured to use it properly.)
<sageplot> to produce a graphic<!--********************************************************************
Copyright (C) 2019-2026 Robert A. Beezer
This file is part of PreTeXt.
PreTeXt is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 or version 3 of the
License (at your option).
PreTeXt is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with PreTeXt. If not, see <http://www.gnu.org/licenses/>.
*****************************************************************-->
<figure xml:id="fig-sage-cubic">
<caption>A cubic plotted by SageMath on
<m>[-3,2]</m></caption>
<image xml:id="sageplot-cubic" width="50%">
<description><p>A cubic function on the interval
[-3,2]</p></description>
<sageplot>
f(x) = (x-1)*(x+1)*(x-2)
plot(f, (x, -3, 2), color='blue', thickness=3)
</sageplot>
</image>
</figure>
We need to run the
pretext script to actually make the image files required. If you want to make both HTML and PDF via LaTeX, 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 LaTeX. 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/pretext/pretext/pretext -c sageplot -f svg -d ./images /path/to/yoursource.ptx
$ /path/to/pretext/pretext/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]
