Plotting PDF
Plotting PDF
Release 8.8
1 General 1
1.1 2D Plotting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Text in plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
1.3 Colors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
1.4 Animated plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
i
Python Module Index 419
Index 421
ii
CHAPTER
ONE
GENERAL
1.1 2D Plotting
Sage provides extensive 2D plotting functionality. The underlying rendering is done using the matplotlib Python
library.
The following graphics primitives are supported:
• arrow() - an arrow from a min point to a max point.
• circle() - a circle with given radius
• ellipse() - an ellipse with given radii and angle
• arc() - an arc of a circle or an ellipse
• disk() - a filled disk (i.e. a sector or wedge of a circle)
• line() - a line determined by a sequence of points (this need not be straight!)
• point() - a point
• text() - some text
• polygon() - a filled polygon
The following plotting functions are supported:
• plot() - plot of a function or other Sage object (e.g., elliptic curve).
• parametric_plot()
• implicit_plot()
• polar_plot()
• region_plot()
• list_plot()
• scatter_plot()
• bar_chart()
• contour_plot()
• density_plot()
• plot_vector_field()
• plot_slope_field()
• matrix_plot()
1
Sage Reference Manual: 2D Graphics, Release 8.8
• complex_plot()
• graphics_array()
• The following log plotting functions:
– plot_loglog()
– plot_semilogx() and plot_semilogy()
– list_plot_loglog()
– list_plot_semilogx() and list_plot_semilogy()
The following miscellaneous Graphics functions are included:
• Graphics()
• is_Graphics()
• hue()
Type ? after each primitive in Sage for help and examples.
EXAMPLES:
We draw a curve:
25
20
15
10
1 2 3 4 5
2 Chapter 1. General
Sage Reference Manual: 2D Graphics, Release 8.8
25
20
15
10
12345
Notice that the aspect ratio of the above plot makes the plot very tall because the plot adopts the default aspect ratio of
the circle (to make the circle appear like a circle). We can change the aspect ratio to be what we normally expect for a
plot by explicitly asking for an ‘automatic’ aspect ratio:
The aspect ratio describes the apparently height/width ratio of a unit square. If you want the vertical units to be twice
as big as the horizontal units, specify an aspect ratio of 2:
The figsize option adjusts the figure size. The default figsize is 4. To make a figure that is roughly twice as big,
use figsize=8:
You can also give separate horizontal and vertical dimensions. Both will be measured in inches:
1.1. 2D Plotting 3
Sage Reference Manual: 2D Graphics, Release 8.8
However, do not make the figsize too big (e.g. one dimension greater than 327 or both in the mid-200s) as this will
lead to errors or crashes. See show() for full details.
Note that the axes will not cross if the data is not on both sides of both axes, even if it is quite close:
1000
800
600
400
200
0
2 4 6 8 10
When the labels have quite different orders of magnitude or are very large, scientific notation (the 𝑒 notation for powers
of ten) is used:
But you can fix your own tick labels, if you know what to expect and have a preference:
To change the ticks on one axis only, use the following notation:
4 Chapter 1. General
Sage Reference Manual: 2D Graphics, Release 8.8
250000
245000
240000
235000
230000
480 485 490 495 500
1.1. 2D Plotting 5
Sage Reference Manual: 2D Graphics, Release 8.8
2.4e5
2.2e5
2e5
1.8e5
1.6e5
1.4e5
1.2e5
1e5
6 Chapter 1. General
Sage Reference Manual: 2D Graphics, Release 8.8
2.5e5
2e5
1.5e5
1e5
1.1. 2D Plotting 7
Sage Reference Manual: 2D Graphics, Release 8.8
2.5e5
2e5
1.5e5
1e5
Next we construct the reflection of the above polygon about the 𝑦-axis by iterating over the list of first-coordinates of
the first graphic element of P (which is the actual Polygon; note that P is a Graphics object, which consists of a single
polygon):
8 Chapter 1. General
Sage Reference Manual: 2D Graphics, Release 8.8
5π
2
2π
3π
2
1π
2
x1 x2
1.1. 2D Plotting 9
Sage Reference Manual: 2D Graphics, Release 8.8
A plot
6
-4 -2 2 4
-1
10 Chapter 1. General
Sage Reference Manual: 2D Graphics, Release 8.8
0
-5 -4.5 -4 -3.5 -3 -2.5 -2 -1.5 -1
1.1. 2D Plotting 11
Sage Reference Manual: 2D Graphics, Release 8.8
sage: H = G + P + Q
sage: print(H)
Graphics object consisting of 3 graphics primitives
sage: type(H)
<class 'sage.plot.graphics.Graphics'>
sage: H[1]
Polygon defined by 3 points
sage: list(H[1])
[(1.0, 2.0), (5.0, 6.0), (5.0, 0.0)]
sage: H # show it
Graphics object consisting of 3 graphics primitives
A plot
6
-4 -2 2 4
-1
12 Chapter 1. General
Sage Reference Manual: 2D Graphics, Release 8.8
1
y axis
0.5
A Bulb
-0.5
-1
1.1. 2D Plotting 13
Sage Reference Manual: 2D Graphics, Release 8.8
sage: x = var('x')
sage: plot(x^2, (x,-2,2), title='A plot of $x^2$')
Graphics object consisting of 1 graphics primitive
A plot of x 2
4
3.5
2.5
1.5
0.5
We plot the Riemann zeta function along the critical line and see the first few zeros:
sage: i = CDF.0 # define i this way for maximum speed.
sage: p1 = plot(lambda t: arg(zeta(0.5+t*i)), 1, 27, rgbcolor=(0.8,0,0))
sage: p2 = plot(lambda t: abs(zeta(0.5+t*i)), 1, 27, color=hue(0.7))
sage: print(p1 + p2)
Graphics object consisting of 2 graphics primitives
sage: p1 + p2 # display it
Graphics object consisting of 2 graphics primitives
Note: Not all functions in Sage are symbolic. When plotting non-symbolic functions they should be wrapped in
lambda:
sage: plot(lambda x:fibonacci(round(x)), (x,1,10))
Graphics object consisting of 1 graphics primitive
14 Chapter 1. General
Sage Reference Manual: 2D Graphics, Release 8.8
3.5
2.5
1.5
0.5
1.1. 2D Plotting 15
Sage Reference Manual: 2D Graphics, Release 8.8
0
5 10 15 20 25
-1
16 Chapter 1. General
Sage Reference Manual: 2D Graphics, Release 8.8
50
40
30
20
10
0
2 4 6 8 10
Many concentric circles shrinking toward the origin:
sage: show(sum(circle((i,0), i, hue=sin(i/10)) for i in [10,9.9,..,0])) # long time
Another graph:
sage: x = var('x')
sage: P = plot(sin(x)/x, -4, 4, color='blue') + \
....: plot(x*cos(x), -4, 4, color='red') + \
....: plot(tan(x), -4, 4, color='green')
sage: P.show(ymin=-pi, ymax=pi)
PYX EXAMPLES: These are some examples of plots similar to some of the plots in the PyX (http://pyx.sourceforge.
net) documentation:
Symbolline:
1.1. 2D Plotting 17
Sage Reference Manual: 2D Graphics, Release 8.8
10
5 10 15 20
-5
-10
18 Chapter 1. General
Sage Reference Manual: 2D Graphics, Release 8.8
1.1. 2D Plotting 19
Sage Reference Manual: 2D Graphics, Release 8.8
-4 -3 -2 -1 1 2 3 4
-1
-2
-3
20 Chapter 1. General
Sage Reference Manual: 2D Graphics, Release 8.8
-3 -2 -1 1 2 3
-1
-2
Cycliclink:
sage: x = var('x')
sage: g1 = plot(cos(20*x)*exp(-2*x), 0, 1)
sage: g2 = plot(2*exp(-30*x) - exp(-3*x), 0, 1)
sage: show(graphics_array([g1, g2], 2, 1), xmin=0)
Pi Axis:
An illustration of integration:
1.1. 2D Plotting 21
Sage Reference Manual: 2D Graphics, Release 8.8
0.5
-0.5
1
0.8
0.6
0.4
0.2
0.2 0.4 0.6 0.8 1
-0.2
-0.4
-0.6
22 Chapter 1. General
Sage Reference Manual: 2D Graphics, Release 8.8
1.0
0.5
1π
6
1π
3
1π
2
2π
3
5π
6
π 7π
6
4π
3
3π
2
5π
3
11 π
6
2π
−0.5
−1.0
1.1. 2D Plotting 23
Sage Reference Manual: 2D Graphics, Release 8.8
70
60
50
40
30
Z b
20 f(x)dx
a
10
0
1 2 3 4 5 6 7 8
NUMERICAL PLOTTING:
Sage includes Matplotlib, which provides 2D plotting with an interface that is a likely very familiar to people doing
numerical computation. You can use plt.clf() to clear the current image frame and plt.close() to close it.
For example,
sage: import pylab as plt
sage: t = plt.arange(0.0, 2.0, 0.01)
sage: s = sin(2*pi*t)
sage: P = plt.plot(t, s, linewidth=1.0)
sage: xl = plt.xlabel('time (s)')
sage: yl = plt.ylabel('voltage (mV)')
sage: t = plt.title('About as simple as it gets, folks')
sage: plt.grid(True)
sage: plt.savefig(os.path.join(SAGE_TMP, 'sage.png'))
sage: plt.clf()
sage: plt.savefig(os.path.join(SAGE_TMP, 'blank.png'))
(continues on next page)
24 Chapter 1. General
Sage Reference Manual: 2D Graphics, Release 8.8
We test that imshow works as well, verifying that trac ticket #2900 is fixed (in Matplotlib).
sage: plt.imshow([[(0.0,0.0,0.0)]])
<matplotlib.image.AxesImage object at ...>
sage: plt.savefig(os.path.join(SAGE_TMP, 'foo.png'))
Since the above overwrites many Sage plotting functions, we reset the state of Sage, so that the examples below work!
sage: reset()
AUTHORS:
• Alex Clemesha and William Stein (2006-04-10): initial version
• David Joyner: examples
• Alex Clemesha (2006-05-04) major update
• William Stein (2006-05-29): fine tuning, bug fixes, better server integration
• William Stein (2006-07-01): misc polish
• Alex Clemesha (2006-09-29): added contour_plot, frame axes, misc polishing
• Robert Miller (2006-10-30): tuning, NetworkX primitive
• Alex Clemesha (2006-11-25): added plot_vector_field, matrix_plot, arrow, bar_chart, Axes class usage (see
axes.py)
• Bobby Moretti and William Stein (2008-01): Change plot to specify ranges using the (varname, min, max)
notation.
• William Stein (2008-01-19): raised the documentation coverage from a miserable 12 percent to a ‘wopping’ 35
percent, and fixed and clarified numerous small issues.
• Jason Grout (2009-09-05): shifted axes and grid functionality over to matplotlib; fixed a number of smaller
issues.
• Jason Grout (2010-10): rewrote aspect ratio portions of the code
• Jeroen Demeyer (2012-04-19): move parts of this file to graphics.py (trac ticket #12857)
• Aaron Lauve (2016-07-13): reworked handling of ‘color’ when passed a list of functions; now more in-line with
other CAS’s. Added list functionality to linestyle and legend_label options as well. (trac ticket #12962)
sage.plot.plot.SelectiveFormatter(formatter, skip_values)
This matplotlib formatter selectively omits some tick values and passes the rest on to a specified formatter.
1.1. 2D Plotting 25
Sage Reference Manual: 2D Graphics, Release 8.8
EXAMPLES:
This example is almost straight from a matplotlib example.
sage: ax.xaxis.set_major_formatter(formatter)
sage: fig.savefig(os.path.join(SAGE_TMP, 'test.png'))
sage: x = var('x')
sage: f(x) = sin(1/x)
sage: n1 = len(adaptive_refinement(f, (0,0), (pi,0), adaptive_tolerance=0.01)); n1
15
sage: n2 = len(adaptive_refinement(f, (0,0), (pi,0), adaptive_recursion=10,
˓→adaptive_tolerance=0.01)); n2
79
sage: n3 = len(adaptive_refinement(f, (0,0), (pi,0), adaptive_tolerance=0.001));
˓→n3
26
26 Chapter 1. General
Sage Reference Manual: 2D Graphics, Release 8.8
• plot_points - (default: 5) the minimal number of plot points. (Note however that in any actual plot a
number is passed to this, with default value 200.)
• adaptive_recursion - (default: 5) how many levels of recursion to go before giving up when doing
adaptive refinement. Setting this to 0 disables adaptive refinement.
• adaptive_tolerance - (default: 0.01) how large the relative difference should be before the adaptive
refinement code considers it significant. If the actual difference is greater than adaptive_tolerance*delta,
where delta is the initial subinterval size for the given xrange and plot_points, then the algorithm will
consider it significant.
• initial_points - (default: None) a list of points that should be evaluated.
OUTPUT:
• a list of points (x, f(x)) in the interval xrange, which approximate the function f.
sage: x = var('x')
sage: f(x) = sin(1/x)
sage: [len(generate_plot_points(f, (-pi, pi), plot_points=16, adaptive_
˓→tolerance=i, randomize=False)) for i in [0.01, 0.001, 0.0001]]
One can also name the array, and then use show() or save():
1.1. 2D Plotting 27
Sage Reference Manual: 2D Graphics, Release 8.8
1 1
0.5 0.5
-6 -4 -2 2 4 6 -6 -4 -2 2 4 6
-0.5 -0.5
-1 -1
1 1
0.5 0.5
-1 -1
28 Chapter 1. General
Sage Reference Manual: 2D Graphics, Release 8.8
sage: p1 = plot(sin,(-4,4))
sage: p2 = plot(cos,(-4,4))
sage: g = graphics_array([p1, p2]); print(g)
Graphics Array of size 1 x 2
sage: g.show()
1 1
0.5 0.5
-4 -3 -2 -1 1 2 3 4 -4 -3 -2 -1 1 2 3 4
-0.5 -0.5
-1 -1
It is possible to use figsize to change the size of the plot as a whole:
Specifying only the number of rows or the number of columns computes the other dimension automatically:
1.1. 2D Plotting 29
Sage Reference Manual: 2D Graphics, Release 8.8
list_plot takes either a list of numbers, a list of tuples, a numpy array, or a dictionary and plots the corre-
sponding points.
If given a list of numbers (that is, not a list of tuples or lists), list_plot forms a list of tuples (i, x_i)
where i goes from 0 to len(data)-1 and x_i is the i-th data value, and puts points at those tuple values.
list_plot will plot a list of complex numbers in the obvious way; any numbers for which CC() makes sense
will work.
list_plot also takes a list of tuples (x_i, y_i) where x_i and y_i are the i-th values representing the
x- and y-values, respectively.
If given a dictionary, list_plot interprets the keys as 𝑥-values and the values as 𝑦-values.
The plotjoined=True option tells list_plot to plot a line joining all the data.
For other keyword options that the list_plot function can take, refer to plot().
It is possible to pass empty dictionaries, lists, or tuples to list_plot. Doing so will plot nothing (returning
an empty plot).
EXAMPLES:
16
14
12
10
30 Chapter 1. General
Sage Reference Manual: 2D Graphics, Release 8.8
0.8
0.6
0.4
0.2
1.1. 2D Plotting 31
Sage Reference Manual: 2D Graphics, Release 8.8
0.8
0.6
0.4
0.2
0
0.2 0.4 0.6 0.8 1
32 Chapter 1. General
Sage Reference Manual: 2D Graphics, Release 8.8
2 4 6 8
1.1. 2D Plotting 33
Sage Reference Manual: 2D Graphics, Release 8.8
3.5
2.5
2
1 1.5 2 2.5 3
34 Chapter 1. General
Sage Reference Manual: 2D Graphics, Release 8.8
0.8
0.6
0.4
0.2
1.1. 2D Plotting 35
Sage Reference Manual: 2D Graphics, Release 8.8
0.8
0.6
0.4
0.2
-1 -0.5 0.5 1
Note that if your list of complex numbers are all actually real, they get plotted as real values, so this
sage: list_plot([CDF(1), CDF(1/2), CDF(1/3)])
Graphics object consisting of 1 graphics primitive
is the same as list_plot([1, 1/2, 1/3]) – it produces a plot of the points (0, 1), (1, 1/2), and (2, 1/3).
If you have separate lists of 𝑥 values and 𝑦 values which you want to plot against each other, use the zip
command to make a single list whose entries are pairs of (𝑥, 𝑦) values, and feed the result into list_plot:
sage: x_coords = [cos(t)^3 for t in srange(0, 2*pi, 0.02)]
sage: y_coords = [sin(t)^3 for t in srange(0, 2*pi, 0.02)]
sage: list_plot(list(zip(x_coords, y_coords)))
Graphics object consisting of 1 graphics primitive
If instead you try to pass the two lists as separate arguments, you will get an error message:
sage: list_plot(x_coords, y_coords)
Traceback (most recent call last):
...
TypeError: The second argument 'plotjoined' should be boolean (True or False).
˓→If you meant to plot two lists 'x' and 'y' against each other, use 'list_
36 Chapter 1. General
Sage Reference Manual: 2D Graphics, Release 8.8
0.8
0.6
0.4
0.2
0.5 1 1.5 2
1.1. 2D Plotting 37
Sage Reference Manual: 2D Graphics, Release 8.8
0.5
-1 -0.5 0.5 1
-0.5
-1
38 Chapter 1. General
Sage Reference Manual: 2D Graphics, Release 8.8
sage: list_plot({22: 3365, 27: 3295, 37: 3135, 42: 3020, 47: 2880, 52: 2735, 57:
˓→2550})
3300
3200
3100
3000
2900
2800
2700
2600
25 30 35 40 45 50 55
Plotting in logarithmic scale is possible for 2D list plots. There are two different syntaxes available:
Warning: If plotjoined is False then the axis that is in log scale must have all points strictly positive.
For instance, the following plot will show no points in the figure since the points in the horizontal axis starts
from (0, 1). Further, matplotlib will display a user warning.
1.1. 2D Plotting 39
Sage Reference Manual: 2D Graphics, Release 8.8
105
104
103
102
101
100
0 5 10 15
40 Chapter 1. General
Sage Reference Manual: 2D Graphics, Release 8.8
21818
21515
21212
299
266
233
200
2-1 20 21 22 23 24
We can also change the scale of the axes in the graphics just before displaying:
1.1. 2D Plotting 41
Sage Reference Manual: 2D Graphics, Release 8.8
INPUT:
• base – (default: 10) the base of the logarithm. This must be greater than 1. The base can be also given
as a list or tuple (basex, basey). basex sets the base of the logarithm along the horizontal axis and
basey sets the base along the vertical axis.
For all other inputs, look at the documentation of list_plot().
EXAMPLES:
sage: yl = [5**k for k in range(10)]; xl = [2**k for k in range(10)]
sage: list_plot_loglog(list(zip(xl, yl))) # long time # plot in loglog scale with
˓→base 10
106
105
104
103
102
101
100
100 101 102
sage: list_plot_loglog(list(zip(xl, yl)), base=2.1) # long time # with base 2.1
˓→on both axes
Warning: If plotjoined is False then the axis that is in log scale must have all points strictly positive.
For instance, the following plot will show no points in the figure since the points in the horizontal axis starts
42 Chapter 1. General
Sage Reference Manual: 2D Graphics, Release 8.8
2.120
2.117
2.114
2.111
2.18
2.15
2.12
1.1. 2D Plotting 43
Sage Reference Manual: 2D Graphics, Release 8.8
2000
1500
1000
500
0
100 101 102 103
44 Chapter 1. General
Sage Reference Manual: 2D Graphics, Release 8.8
Warning: If plotjoined is False then the horizontal axis must have all points strictly positive. Other-
wise the plot will come up empty. For instance the following plot contains a point at (0, 1).
sage: yl = [2**k for k in range(12)]
sage: list_plot_semilogx(yl) # plot empty due to (0,1)
Graphics object consisting of 1 graphics primitive
0
2-1 20 21 22 23 24 25
-1
sage.plot.plot.list_plot_semilogy(data, plotjoined=False, base=10, **kwds)
Plot data in ‘semilogy’ scale, that is, the vertical axis will be in logarithmic scale.
INPUT:
• base – (default: 10) the base of the logarithm. This must be greater than 1.
For all other inputs, look at the documentation of list_plot().
EXAMPLES:
1.1. 2D Plotting 45
Sage Reference Manual: 2D Graphics, Release 8.8
103
102
101
100
0 2 4 6 8 10
Warning: If plotjoined is False then the vertical axis must have all points strictly positive. Otherwise
the plot will come up empty. For instance the following plot contains a point at (1, 0). Further, matplotlib
will display a user warning.
sage: xl = [2**k for k in range(12)]; yl = range(len(xl))
sage: list_plot_semilogy(list(zip(xl,yl))) # plot empty due to (1,0)
doctest:warning
...
Graphics object consisting of 1 graphics primitive
46 Chapter 1. General
Sage Reference Manual: 2D Graphics, Release 8.8
255
244
233
222
211
200
0 1 2 3 4 5
1.1. 2D Plotting 47
Sage Reference Manual: 2D Graphics, Release 8.8
sage: t = var('t')
sage: parametric_plot( (cos(t), sin(t)), (t, 0, 2*pi))
Graphics object consisting of 1 graphics primitive
A filled Hypotrochoid:
48 Chapter 1. General
Sage Reference Manual: 2D Graphics, Release 8.8
0.5
-1 -0.5 0.5 1
-0.5
-1
1.1. 2D Plotting 49
Sage Reference Manual: 2D Graphics, Release 8.8
0.5
-1 -0.5 0.5 1
-0.5
-1
50 Chapter 1. General
Sage Reference Manual: 2D Graphics, Release 8.8
3.5
2.5
1.5
0.5
0.5 1 1.5 2
1.1. 2D Plotting 51
Sage Reference Manual: 2D Graphics, Release 8.8
16
14
12
10
-4 -3 -2 -1 1 2 3 4
52 Chapter 1. General
Sage Reference Manual: 2D Graphics, Release 8.8
-2 -1 1 2 3
-1
-2
Graphics3d Object
sage: y=var('y')
sage: parametric_plot( (5*cos(x), x*y, cos(x*y)), (x, -4,4), (y,-4,4)) # long
˓→time`
Graphics3d Object
sage: t=var('t')
sage: parametric_plot( vector((sin(t), sin(2*t))), (t, 0, 2*pi), color='green') #
˓→long time
sage: t = var('t')
sage: parametric_plot( vector([t, t+1, t^2]), (t, 0, 1)) # long time
Graphics3d Object
Plotting in logarithmic scale is possible with 2D plots. The keyword aspect_ratio will be ignored if the
scale is not 'loglog' or 'linear'.:
1.1. 2D Plotting 53
Sage Reference Manual: 2D Graphics, Release 8.8
0.5
-1 -0.5 0.5 1
-0.5
-1
54 Chapter 1. General
Sage Reference Manual: 2D Graphics, Release 8.8
102
101
100
100 101
We can also change the scale of the axes in the graphics just before displaying. In this case, the aspect_ratio
must be specified as 'automatic' if the scale is set to 'semilogx' or 'semilogy'. For other values
of the scale parameter, any aspect_ratio can be used, or the keyword need not be provided.:
1.1. 2D Plotting 55
Sage Reference Manual: 2D Graphics, Release 8.8
PLOT OPTIONS:
• plot_points - (default: 200) the minimal number of plot points.
• adaptive_recursion - (default: 5) how many levels of recursion to go before giving up when doing
adaptive refinement. Setting this to 0 disables adaptive refinement.
• adaptive_tolerance - (default: 0.01) how large a difference should be before the adaptive refine-
ment code considers it significant. See the documentation further below for more information, starting at
“the algorithm used to insert”.
• base - (default: 10) the base of the logarithm if a logarithmic scale is set. This must be greater than 1.
The base can be also given as a list or tuple (basex, basey). basex sets the base of the logarithm
along the horizontal axis and basey sets the base along the vertical axis.
• scale – (default: "linear") string. The scale of the axes. Possible values are "linear",
"loglog", "semilogx", "semilogy".
The scale can be also be given as single argument that is a list or tuple (scale, base) or (scale,
basex, basey).
The "loglog" scale sets both the horizontal and vertical axes to logarithmic scale. The "semilogx"
scale sets the horizontal axis to logarithmic scale. The "semilogy" scale sets the vertical axis to loga-
rithmic scale. The "linear" scale is the default value when Graphics is initialized.
• xmin - starting x value in the rendered figure. This parameter is passed directly to the show procedure
and it could be overwritten.
• xmax - ending x value in the rendered figure. This parameter is passed directly to the show procedure
and it could be overwritten.
• ymin - starting y value in the rendered figure. This parameter is passed directly to the show procedure
and it could be overwritten.
• ymax - ending y value in the rendered figure. This parameter is passed directly to the show procedure
and it could be overwritten.
• detect_poles - (Default: False) If set to True poles are detected. If set to “show” vertical asymptotes
are drawn.
• legend_label - a (TeX) string serving as the label for 𝑋 in the legend. If 𝑋 is a list, then this option
can be a single string, or a list or dictionary with strings as entries/values. If a dictionary, then keys are
taken from range(len(X)).
Note:
• If the scale is "linear", then irrespective of what base is set to, it will default to 10 and will remain
unused.
• If you want to limit the plot along the horizontal axis in the final rendered figure, then pass the xmin
and xmax keywords to the show() method. To limit the plot along the vertical axis, ymin and ymax
keywords can be provided to either this plot command or to the show command.
• This function does NOT simply sample equally spaced points between xmin and xmax. Instead it computes
equally spaced points and adds small perturbations to them. This reduces the possibility of, e.g., sampling
sin only at multiples of 2𝜋, which would yield a very misleading graph.
• If there is a range of consecutive points where the function has no value, then those points will be excluded
from the plot. See the example below on automatic exclusion of points.
• For the other keyword options that the plot function can take, refer to the method show() and the
further options below.
56 Chapter 1. General
Sage Reference Manual: 2D Graphics, Release 8.8
COLOR OPTIONS:
• color - (Default: ‘blue’) One of:
– an RGB tuple (r,g,b) with each of r,g,b between 0 and 1.
– a color name as a string (e.g., ‘purple’).
– an HTML color such as ‘#aaff0b’.
– a list or dictionary of colors (valid only if 𝑋 is a list): if a dictionary, keys are taken from
range(len(X)); the entries/values of the list/dictionary may be any of the options above.
– ‘automatic’ – maps to default (‘blue’) if 𝑋 is a single Sage object; and maps to a fixed sequence of
regularly spaced colors if 𝑋 is a list.
• legend_color - the color of the text for 𝑋 (or each item in 𝑋) in the legend. Default color is
‘black’. Options are as in color above, except that the choice ‘automatic’ maps to ‘black’ if 𝑋 is a
single Sage object.
• fillcolor - The color of the fill for the plot of 𝑋 (or each item in 𝑋). Default color is ‘gray’ if 𝑋
is a single Sage object or if color is a single color. Otherwise, options are as in color above.
APPEARANCE OPTIONS:
The following options affect the appearance of the line through the points on the graph of 𝑋 (these are the same
as for the line function):
INPUT:
• alpha - How transparent the line is
• thickness - How thick the line is
• rgbcolor - The color as an RGB tuple
• hue - The color given as a hue
LINE OPTIONS:
Any MATPLOTLIB line option may also be passed in. E.g.,
• linestyle - (default: “-“) The style of the line, which is one of
– "-" or "solid"
– "--" or "dashed"
– "-." or "dash dot"
– ":" or "dotted"
– "None" or " " or "" (nothing)
– a list or dictionary (see below)
The linestyle can also be prefixed with a drawing style (e.g., "steps--")
– "default" (connect the points with straight lines)
– "steps" or "steps-pre" (step function; horizontal line is to the left of point)
– "steps-mid" (step function; points are in the middle of horizontal lines)
– "steps-post" (step function; horizontal line is to the right of point)
1.1. 2D Plotting 57
Sage Reference Manual: 2D Graphics, Release 8.8
If 𝑋 is a list, then linestyle may be a list (with entries taken from the strings above) or a dictionary
(with keys in range(len(X)) and values taken from the strings above).
• marker - The style of the markers, which is one of
– "None" or " " or "" (nothing) – default
– "," (pixel), "." (point)
– "_" (horizontal line), "|" (vertical line)
– "o" (circle), "p" (pentagon), "s" (square), "x" (x), "+" (plus), "*" (star)
– "D" (diamond), "d" (thin diamond)
– "H" (hexagon), "h" (alternative hexagon)
– "<" (triangle left), ">" (triangle right), "^" (triangle up), "v" (triangle down)
– "1" (tri down), "2" (tri up), "3" (tri left), "4" (tri right)
– 0 (tick left), 1 (tick right), 2 (tick up), 3 (tick down)
– 4 (caret left), 5 (caret right), 6 (caret up), 7 (caret down), 8 (octagon)
– "$...$" (math TeX string)
– (numsides, style, angle) to create a custom, regular symbol
58 Chapter 1. General
Sage Reference Manual: 2D Graphics, Release 8.8
• stylesheet - (Default: classic) Support for loading a full matplotlib style sheet. Any style sheet listed
in matplotlib.pyplot.style.available is acceptable. If a non-existing style is provided the
default classic is applied.
EXAMPLES:
We plot the sin function:
0.5
2 4 6 8 10
-0.5
-1
sage: P = plot(sin, (0,10), plot_points=10); print(P)
Graphics object consisting of 1 graphics primitive
sage: len(P[0]) # random output
32
sage: P # render
Graphics object consisting of 1 graphics primitive
We plot with randomize=False, which makes the initial sample points evenly spaced (hence always the
same). Adaptive plotting might insert other points, however, unless adaptive_recursion=0.
1.1. 2D Plotting 59
Sage Reference Manual: 2D Graphics, Release 8.8
0.5
2 4 6 8 10
-0.5
-1
60 Chapter 1. General
Sage Reference Manual: 2D Graphics, Release 8.8
0.5
2 4 6 8 10
-0.5
-1
sage: plot(sin, 0, 10, color='#ff00ff')
Graphics object consisting of 1 graphics primitive
By default, color will change from one primitive to the next. This may be controlled by modifying color
option:
1.1. 2D Plotting 61
Sage Reference Manual: 2D Graphics, Release 8.8
0.5
2 4 6 8 10
-0.5
-1
62 Chapter 1. General
Sage Reference Manual: 2D Graphics, Release 8.8
0.8
0.6
0.4
0.2
0.5 1 1.5 2
1.1. 2D Plotting 63
Sage Reference Manual: 2D Graphics, Release 8.8
1
0.8
0.6
0.4
0.2
0.5 1 1.5 2
1
0.8
0.6
0.4
0.2
0.5 1 1.5 2
We can also build a plot step by step from an empty plot:
The function sin(1/𝑥) wiggles wildly near 0. Sage adapts to this and plots extra points near the origin.
Via the matplotlib library, Sage makes it easy to tell whether a graph is on both sides of both axes, as the axes
only cross if the origin is actually part of the viewing area:
64 Chapter 1. General
Sage Reference Manual: 2D Graphics, Release 8.8
0.8
0.6
0.4
0.2
-1 -0.5 0.5 1
1.1. 2D Plotting 65
Sage Reference Manual: 2D Graphics, Release 8.8
0.5
-1 -0.5 0.5 1
-0.5
-1
66 Chapter 1. General
Sage Reference Manual: 2D Graphics, Release 8.8
0.5
-1 -0.5 0.5 1
-0.5
-1
1.1. 2D Plotting 67
Sage Reference Manual: 2D Graphics, Release 8.8
0.5 1 1.5 2
sage: plot(x^3,(x,1,2)) # this one does not
Graphics object consisting of 1 graphics primitive
Another thing to be aware of with axis labeling is that when the labels have quite different orders of magnitude
or are very large, scientific notation (the 𝑒 notation for powers of ten) is used:
sage: plot(x^2,(x,480,500)) # this one has no scientific notation
Graphics object consisting of 1 graphics primitive
You can put a legend with legend_label (the legend is only put once in the case of multiple functions):
sage: plot(exp(x), 0, 2, legend_label='$e^x$')
Graphics object consisting of 1 graphics primitive
Sage understands TeX, so these all are slightly different, and you can choose one based on your needs:
sage: plot(sin, legend_label='sin')
Graphics object consisting of 1 graphics primitive
68 Chapter 1. General
Sage Reference Manual: 2D Graphics, Release 8.8
1
1 1.2 1.4 1.6 1.8 2
1.1. 2D Plotting 69
Sage Reference Manual: 2D Graphics, Release 8.8
250000
245000
240000
235000
230000
480 485 490 495 500
70 Chapter 1. General
Sage Reference Manual: 2D Graphics, Release 8.8
2.4e5
2.2e5
2e5
1.8e5
1.6e5
1.4e5
1.2e5
1e5
1.1. 2D Plotting 71
Sage Reference Manual: 2D Graphics, Release 8.8
ex
7
1
0 0.5 1 1.5 2
72 Chapter 1. General
Sage Reference Manual: 2D Graphics, Release 8.8
sin 0.8
0.6
0.4
0.2
-1 -0.5 0.5 1
-0.2
-0.4
-0.6
-0.8
1.1. 2D Plotting 73
Sage Reference Manual: 2D Graphics, Release 8.8
sin 0.8
0.6
0.4
0.2
-1 -0.5 0.5 1
-0.2
-0.4
-0.6
-0.8
Prior to trac ticket #19485, legends by default had a shadowless gray background. This behavior can be recov-
ered by setting the legend options on your plot object:
If 𝑋 is a list of Sage objects and legend_label is ‘automatic’, then Sage will create labels for each function
according to their internal representation:
74 Chapter 1. General
Sage Reference Manual: 2D Graphics, Release 8.8
sin 0.8
0.6
0.4
0.2
-1 -0.5 0.5 1
-0.2
-0.4
-0.6
-0.8
1.1. 2D Plotting 75
Sage Reference Manual: 2D Graphics, Release 8.8
sin 1
cos
0.5
-1 -0.5 0.5 1
-0.5
76 Chapter 1. General
Sage Reference Manual: 2D Graphics, Release 8.8
sin(x) 0.8
0.6
0.4
0.2
-1 -0.5 0.5 1
-0.2
-0.4
-0.6
-0.8
1.1. 2D Plotting 77
Sage Reference Manual: 2D Graphics, Release 8.8
sin(x) 1.5
tan(x)
-x^2 + 1
1
0.5
-1 -0.5 0.5 1
-0.5
-1
-1.5
78 Chapter 1. General
Sage Reference Manual: 2D Graphics, Release 8.8
If legend_label is any single string other than ‘automatic’, then it is repeated for all members of 𝑋:
sage: plot([sin(x), tan(x)], color='blue', legend_label='trig')
Graphics object consisting of 2 graphics primitives
trig 1.5
trig
0.5
-1 -0.5 0.5 1
-0.5
-1
-1.5
Plotting in logarithmic scale is possible for 2D plots. There are two different syntaxes supported:
sage: plot(exp, (1, 10), scale='semilogy') # log axis on vertical
Graphics object consisting of 1 graphics primitive
sage: plot(exp, (1, 10), scale='loglog', base=2) # long time # base of log is 2
Graphics object consisting of 1 graphics primitive
We can also change the scale of the axes in the graphics just before displaying:
1.1. 2D Plotting 79
Sage Reference Manual: 2D Graphics, Release 8.8
0.5
-1 -0.5 0.5 1
-0.5
-1
80 Chapter 1. General
Sage Reference Manual: 2D Graphics, Release 8.8
104
103
102
101
2 4 6 8 10
1.1. 2D Plotting 81
Sage Reference Manual: 2D Graphics, Release 8.8
104
103
102
101
2 4 6 8 10
82 Chapter 1. General
Sage Reference Manual: 2D Graphics, Release 8.8
104
103
102
101
100 101
1.1. 2D Plotting 83
Sage Reference Manual: 2D Graphics, Release 8.8
21414
21212
21010
288
266
244
222
2-1 20 21 22 23
84 Chapter 1. General
Sage Reference Manual: 2D Graphics, Release 8.8
The algorithm used to insert extra points is actually pretty simple. On the picture drawn by the lines below:
D
A
You have the function (in blue) and its approximation (in green) passing through the points A and B. The
algorithm finds the midpoint C of AB and computes the distance between C and D. If that distance exceeds the
adaptive_tolerance threshold (relative to the size of the initial plot subintervals), the point D is added to
the curve. If D is added to the curve, then the algorithm is applied recursively to the points A and D, and D and
B. It is repeated adaptive_recursion times (5, by default).
The actual sample points are slightly randomized, so the above plots may look slightly different each time you
draw them.
We draw the graph of an elliptic curve as the union of graphs of 2 functions.
1.1. 2D Plotting 85
Sage Reference Manual: 2D Graphics, Release 8.8
0
1 1.5 2 2.5 3 3.5 4
-2
-4
-6
-8
It is important to mention that when we draw several graphs at the same time, parameters xmin, xmax, ymin
and ymax are just passed directly to the show procedure. In fact, these parameters would be overwritten:
sage: E = EllipticCurve([0,-1])
sage: plot(E, (1, 4), color=hue(0.6))
Graphics object consisting of 1 graphics primitive
86 Chapter 1. General
Sage Reference Manual: 2D Graphics, Release 8.8
0
1 1.5 2 2.5 3 3.5 4
-2
-4
-6
-8
1.1. 2D Plotting 87
Sage Reference Manual: 2D Graphics, Release 8.8
0.5
2 4 6 8 10
-0.5
-1
If we have an empty linestyle and specify a marker, we can see the points that are actually being plotted:
sage: set_verbose(-1)
sage: plot(-x*log(x), (x,0,1)) # this works fine since the failed endpoint is
˓→just skipped.
This prints out a warning and plots where it can (we turn off the warning by setting the verbose mode temporarily
to -1.)
88 Chapter 1. General
Sage Reference Manual: 2D Graphics, Release 8.8
0.5
2 4 6 8 10
-0.5
-1
1.1. 2D Plotting 89
Sage Reference Manual: 2D Graphics, Release 8.8
0.5
2 4 6 8 10
-0.5
-1
90 Chapter 1. General
Sage Reference Manual: 2D Graphics, Release 8.8
sage: set_verbose(-1)
sage: plot(x^(1/3), (x,-1,1))
Graphics object consisting of 1 graphics primitive
sage: set_verbose(0)
0.9
0.8
0.7
0.6
0.5
0.4
0.3
0.2
A way that points to how to plot other functions without symbolic variants is using lambda functions:
1.1. 2D Plotting 91
Sage Reference Manual: 2D Graphics, Release 8.8
0.5
-1 -0.5 0.5 1
-0.5
-1
92 Chapter 1. General
Sage Reference Manual: 2D Graphics, Release 8.8
1.5
0.5
-4 -3 -2 -1 1 2 3 4
-0.5
-1
-1.5
1.1. 2D Plotting 93
Sage Reference Manual: 2D Graphics, Release 8.8
0.5
-1 -0.5 0.5 1
-0.5
-1
94 Chapter 1. General
Sage Reference Manual: 2D Graphics, Release 8.8
-3 -2 -1 1 2 3 4
-2
-4
1.1. 2D Plotting 95
Sage Reference Manual: 2D Graphics, Release 8.8
-3 -2 -1 1 2 3 4
-2
-4
96 Chapter 1. General
Sage Reference Manual: 2D Graphics, Release 8.8
1 1
0.5 0.5
-3 -2 -1 1 2 3 -3 -2 -1 1 2 3
-0.5 -0.5
-1 -1
1
1
0.5
0.5
-3 -2 -1 1 2 3
-3 -2 -1 1 2 3
-0.5 -0.5
-1 -1
1.1. 2D Plotting 97
Sage Reference Manual: 2D Graphics, Release 8.8
1 1
0.5 0.5
-3 -2 -1 1 2 3 -3 -2 -1 1 2 3
-0.5 -0.5
-1 -1
1 1
0.5 0.5
-3 -2 -1 1 2 3 -3 -2 -1 1 2 3
-0.5 -0.5
-1 -1
98 Chapter 1. General
Sage Reference Manual: 2D Graphics, Release 8.8
20 40 60 80 100
Fill the area between a function and its asymptote:
sage: f = (2*x^3+2*x-1)/((x-2)*(x+1))
sage: plot([f, 2*x+2], -7,7, fill={0: [1]}, fillcolor='#ccc').show(ymin=-20,
˓→ymax=20)
Note that to fill between the ith and jth functions, you must use the dictionary key-value syntax i:[j]; using
key-value pairs like i:j will fill between the ith function and the line y=j:
sage: def b(n): return lambda x: bessel_J(n, x) + 0.5*(n-1)
sage: plot([b(c) for c in [1..5]], 0, 20, fill={i:[i-1] for i in [1..4]}, color=
˓→{i:'blue' for i in [1..5]}, aspect_ratio=3, ymax=3)
1.1. 2D Plotting 99
Sage Reference Manual: 2D Graphics, Release 8.8
20
15
10
-6 -4 -2 2 4 6
-5
-10
-15
-20
0.6
0.4
0.2
5 10 15 20
-0.2
3
2.5
2
1.5
1
0.5
5 10 15 20
3
2.5
2
1.5
1
0.5
5 10 15 20
Extra options will get passed on to show(), as long as they are valid:
This includes options for custom ticks and formatting. See documentation for show() for more details.
Plot of sin(x 2 )
y
1
0.5
x
-3 -2 -1 1 2 3
-0.5
-1
Plot of sin(x^2)
y
1
0.5
x
-3 -2 -1 1 2 3
-0.5
-1
y
1
0.5
-3 -2 -1 1 2 3
x
-0.5
-1
0.5
-3 -2 -1 1 2 3
-0.5
-1
-7 -3 3 7
-1
sage: plot(2*x+1,(x,0,5),ticks=[[0,1,e,pi,sqrt(20)],2],tick_formatter="latex")
Graphics object consisting of 1 graphics primitive
sage: plot(sin(x),(x,0,2*pi),ticks=pi/3,tick_formatter=pi)
Graphics object consisting of 1 graphics primitive
You can even have custom tick labels along with custom positioning.
You can force Type 1 fonts in your figures by providing the relevant option as shown below. This also requires
that LaTeX, dvipng and Ghostscript be installed:
10.0
8.0
6.0
4.0
2.0
p
0 1 e π 2 5
1.0
0.5
1π
3
2π
3
π 4π
3
5π
3
2π
−0.5
−1.0
y3
y2
y1
x1 x2
10
0
2 4 6 8 10
We exclude all points where PrimePi makes a jump:
Regions in which the plot has no values are automatically excluded. The regions thus excluded are in addition
to the exclusion points present in the exclude keyword argument.:
25
20
15
10
20 40 60 80 100
-3 -2 -1 1 2 3 4
-2
-4
-3 -2 -1 1 2 3
-2
-4
sage: set_verbose(-1)
sage: plot(arcsec, (x, -2, 2)) # [-1, 1] is excluded automatically
Graphics object consisting of 2 graphics primitives
2.5
1.5
0.5
0
-2 -1.5 -1 -0.5 0 0.5 1 1.5 2
sage: plot(arcsec, (x, -2, 2), exclude=[1.5]) # x=1.5 is also excluded
Graphics object consisting of 3 graphics primitives
We check various combinations of tuples and functions, ending with tests that lambda functions work properly
with explicit variable declaration, without a tuple.
2.5
1.5
0.5
1.6
1.4
1.2
0.8
0.6
0.4
0.2
0.5
-0.5
-1
We check to handle cases where the function gets evaluated at a point which causes an ‘inf’ or ‘-inf’ result to be
produced.
sage: p = plot(1/x, 0, 1)
sage: p = plot(-1/x, 0, 1)
Check that if excluded points are less than xmin then the exclusion still works for polar and parametric plots.
The following should show two excluded points:
sage: set_verbose(-1)
sage: polar_plot(sin(sqrt(x^2-1)), (x,0,2*pi), exclude=[1/2,2,3])
Graphics object consisting of 3 graphics primitives
sage: set_verbose(0)
Legends can contain variables with long names, trac ticket #13543:
sage: hello = var('hello')
sage: label = '$' + latex(hello) + '$'
(continues on next page)
Extra keywords should be saved if object has a plot method, trac ticket #20924:
sage: G = graphs.PetersenGraph()
sage: p = G.plot()
sage: p.aspect_ratio()
1.0
sage: pp = plot(G)
sage: pp.aspect_ratio()
1.0
sage: plot_loglog(exp, (1,10), base=2.1) # long time # with base 2.1 on both axes
Graphics object consisting of 1 graphics primitive
104
103
102
101
100 101
2.114
2.112
2.110
2.18
2.16
2.14
2.12
39
38
37
36
35
34
33
32
31
2-1 20 21 22 23
20000
15000
10000
5000
0
100 101
20000
15000
10000
5000
0
2-1 20 21 22 23
• base – (default: 10) the base of the logarithm. This must be greater than 1.
• funcs – any Sage object which is acceptable to the plot().
For all other inputs, look at the documentation of plot().
EXAMPLES:
104
103
102
101
2 4 6 8 10
sage: plot_semilogy(exp, (1,10), base=2) # long time # with base 2
Graphics object consisting of 1 graphics primitive
21414
21212
21010
288
266
244
222
2 4 6 8 10
0.5
-0.5 0.5
-0.5
-1
A red figure-8:
sage: polar_plot(abs(sqrt(1 - sin(x)^2)), (x, 0, 2*pi), color='red')
Graphics object consisting of 1 graphics primitive
A filled spiral:
sage: polar_plot(sqrt, 0, 2 * pi, fill=True)
Graphics object consisting of 2 graphics primitives
0.4
0.2
-1 -0.5 0.5 1
-0.2
-0.4
1 2 3 4
-1
-2
1.5
0.5
-0.5
-1
0.5
-0.5
-1
-1.5
-2
-3 -2 -1 1 2 3
-1
-2
-3
Fill the area between several spirals:
sage.plot.plot.reshape(v, n, m)
Helper function for creating graphics arrays.
The input array is flattened and turned into an 𝑛𝑖𝑚𝑒𝑠𝑚 array, with blank graphics object padded at the end, if
necessary.
INPUT:
• v - a list of lists or tuples
• n, m - integers
-4 -2 2 4
-1
-2
-3
-2 -1 1 2
-1
-2
OUTPUT:
A list of lists of graphics objects
EXAMPLES:
sage.plot.plot.to_float_list(v)
Given a list or tuple or iterable v, coerce each element of v to a float and make a list out of the result.
EXAMPLES:
sage.plot.plot.xydata_from_point_list(points)
Returns two lists (xdata, ydata), each coerced to a list of floats, which correspond to the x-coordinates and the
y-coordinates of the points.
The points parameter can be a list of 2-tuples or some object that yields a list of one or two numbers.
This function can potentially be very slow for large point sets.
plot3d(**kwds)
Plots 2D text in 3D.
EXAMPLES:
5.5
5 I like Fibonacci
4.5
4
2 2.5 3 3.5 4
sage: T = text("ABC",(1,1))
sage: t = T[0]
sage: s=t.plot3d()
sage: s.jmol_repr(s.testing_render_params())[0][2]
'label "ABC"'
sage: s._trans
(1.0, 1.0, 0)
sage: text("Sage graphics are really neat because they use matplotlib!", (2,12))
Graphics object consisting of 1 graphics primitive
By setting horizontal_alignment to ‘left’ the text is guaranteed to be in the lower left no matter what:
13
12.5
11.5
11
1 1.5 2 2.5 3
13
12.5
12 I had a dream!
11.5
11
1 1.5 2 2.5 3
0.5
-1 -0.5 0.5 1
-0.5
Various rotations:
0.5
tor
ita
no
-1 -0.5 0.5 1
-0.5
-1
sage: text("Sage is really neat!!",(0,0), rotation="vertical")
Graphics object consisting of 1 graphics primitive
0.5
Sage is really neat!!
-1 -0.5 0.5 1
-0.5
-1
1 Hello
0.9
0.8
0.7
0.6
0.5 World
0 0.5 1 1.5 2
2.5
2 I feel good
1.5
1
0 0.5 1 1.5 2
0.5
So good
-1 -0.5 0.5 1
-0.5
-1
The possible options of the bounding box are ‘boxstyle’ (one of ‘larrow’, ‘rarrow’, ‘round’, ‘round4’, ‘round-
tooth’, ‘sawtooth’, ‘square’), ‘fc’ or ‘facecolor’, ‘ec’ or ‘edgecolor’, ‘ha’ or ‘horizontalalignment’, ‘va’ or ‘ver-
ticalalignment’, ‘lw’ or ‘linewidth’.
A text with a background color:
sage: text("So good", (-2,2), background_color='red')
Graphics object consisting of 1 graphics primitive
Extra options will get passed on to show(), as long as they are valid:
sage: text("MATH IS AWESOME", (0, 0), fontsize=40, axes=False)
Graphics object consisting of 1 graphics primitive
sage: text("MATH IS AWESOME", (0, 0), fontsize=40).show(axes=False) # These are
˓→equivalent (continues on next page)
2.5
So good 2
1.5
1
-3 -2.5 -2 -1.5 -1
1.3 Colors
This module defines a Color object and helper functions (see, e.g., hue(), rainbow()), as well as a set of
colors and colormaps to use with Graphics objects in Sage.
For a list of pre-defined colors in Sage, evaluate:
sage: sorted(colors)
['aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'automatic', ...]
Apart from ‘automatic’ which just an alias for ‘lightblue’, this list comprises the “official” W3C CSS3 / SVG colors.
For a list of color maps in Sage, evaluate:
sage: sorted(colormaps)
[u'Accent', u'Accent_r', u'Blues', u'Blues_r', u'BrBG', u'BrBG_r', ...]
Note: All instantiations of Color are converted to an internal RGB floating point 3-tuple. This is likely to
degrade precision.
INPUT:
• r,g,b - either a triple of floats between 0 and 1, OR r - a color name string or HTML color hex string
• space - a string (default: ‘rgb’); the coordinate system (other choices are ‘hsl’, ‘hls’, and ‘hsv’) in which
to interpret a triple of floats
EXAMPLES:
sage: Color('purple')
RGB color (0.5019607843137255, 0.0, 0.5019607843137255)
sage: Color('#8000ff')
RGB color (0.5019607843137255, 0.0, 1.0)
sage: Color(0.5,0,1)
RGB color (0.5, 0.0, 1.0)
sage: Color(0.5, 1.0, 1, space='hsv')
RGB color (0.0, 1.0, 1.0)
sage: Color(0.25, 0.5, 0.5, space='hls')
RGB color (0.5000000000000001, 0.75, 0.25)
sage: Color(1, 0, 1/3, space='hsl')
RGB color (0.3333333333333333, 0.3333333333333333, 0.3333333333333333)
sage: from sage.plot.colors import chocolate
(continues on next page)
blend(color, fraction=0.5)
Return a color blended with the given color by a given fraction. The algorithm interpolates linearly
between the colors’ corresponding R, G, and B coordinates.
INPUT:
• color - a Color instance or float-convertible 3-tuple/list; the color with which to blend this color
• fraction - a float-convertible number; the fraction of color to blend with this color
OUTPUT:
• a new Color instance
EXAMPLES:
darker(fraction=0.3333333333333333)
Return a darker “shade” of this RGB color by blend()-ing it with black. This is not an inverse of
lighter().
INPUT:
• fraction - a float (default: 1/3); blending fraction to apply
OUTPUT:
• a new instance of Color
EXAMPLES:
hls()
Return the Hue-Lightness-Saturation (HLS) coordinates of this color.
OUTPUT:
• a 3-tuple of floats
EXAMPLES:
hsl()
Return the Hue-Saturation-Lightness (HSL) coordinates of this color.
OUTPUT:
• a 3-tuple of floats
EXAMPLES:
sage: Color(1,0,0).hsl()
(0.0, 1.0, 0.5)
sage: from sage.plot.colors import orchid
sage: orchid.hsl()
(0.8396226415094339, 0.5888888888888889, 0.6470588235294117)
sage: Color('#aabbcc').hsl()
(0.5833333333333334, 0.25000000000000017, 0.7333333333333334)
hsv()
Return the Hue-Saturation-Value (HSV) coordinates of this color.
OUTPUT:
• a 3-tuple of floats
EXAMPLES:
html_color()
Return a HTML hex representation for this color.
OUTPUT:
• a string of length 7.
EXAMPLES:
sage: Color('yellow').html_color()
'#ffff00'
sage: Color('#fedcba').html_color()
'#fedcba'
sage: Color(0.0, 1.0, 0.0).html_color()
'#00ff00'
sage: from sage.plot.colors import honeydew
sage: honeydew.html_color()
'#f0fff0'
lighter(fraction=0.3333333333333333)
Return a lighter “shade” of this RGB color by blend()-ing it with white. This is not an inverse of
darker().
INPUT:
• fraction - a float (default: 1/3); blending fraction to apply
OUTPUT:
• a new instance of Color
EXAMPLES:
rgb()
Return the underlying Red-Green-Blue (RGB) coordinates of this color.
OUTPUT:
• a 3-tuple of floats
EXAMPLES:
class sage.plot.colors.Colormaps
Bases: _abcoll.MutableMapping
A dict-like collection of lazily-loaded matplotlib color maps. For a list of map names, evaluate:
sage: sorted(colormaps)
[u'Accent', u'Accent_r', u'Blues', u'Blues_r', ...]
load_maps()
If it’s necessary, loads matplotlib’s color maps and adds them to the collection.
EXAMPLES:
class sage.plot.colors.ColorsDict
Bases: dict
A dict-like collection of colors, accessible via key or attribute. For a list of color names, evaluate:
sage: sorted(colors)
['aliceblue', 'antiquewhite', 'aqua', 'aquamarine', ...]
sage.plot.colors.check_color_data(cfcm)
Make sure that the arguments are in order (coloring function, colormap).
This will allow users to use both possible orders.
EXAMPLES:
sage.plot.colors.float_to_html(r, g, b)
Convert a Red-Green-Blue (RGB) color tuple to a HTML hex color.
Each input value should be in the interval [0.0, 1.0]; otherwise, the values are first reduced modulo one (see
mod_one()).
INPUT:
• r – a real number; the RGB color’s “red” intensity
• g – a real number; the RGB color’s “green” intensity
• b – a real number; the RGB color’s “blue” intensity
OUTPUT:
• a string of length 7, starting with ‘#’
EXAMPLES:
sage.plot.colors.float_to_integer(r, g, b)
Convert a Red-Green-Blue (RGB) color tuple to an integer.
Each input value should be in the interval [0.0, 1.0]; otherwise, the values are first reduced modulo one (see
mod_one()).
INPUT:
• r – a real number; the RGB color’s “red” intensity
• g – a real number; the RGB color’s “green” intensity
• b – a real number; the RGB color’s “blue” intensity
OUTPUT:
• an integer with encoding 2562 𝑟 + 256𝑔 + 𝑏
EXAMPLES:
sage.plot.colors.get_cmap(cmap)
Returns a color map (actually, a matplotlib Colormap object), given its name or a [mixed] list/tuple of RGB
list/tuples and color names. For a list of map names, evaluate:
sage: sorted(colormaps)
[u'Accent', u'Accent_r', u'Blues', u'Blues_r', ...]
sage: get_cmap('mpl')
Traceback (most recent call last):
...
RuntimeError: Color map mpl not known (type import matplotlib.cm; matplotlib.cm.
˓→datad.keys() for valid names)
sage.plot.colors.html_to_float(c)
Convert a HTML hex color to a Red-Green-Blue (RGB) tuple.
INPUT:
• c - a string; a valid HTML hex color
OUTPUT:
• a RGB 3-tuple of floats in the interval [0.0, 1.0]
EXAMPLES:
sage: p = Graphics()
sage: for phi in xsrange(0, 2 * pi, 1 / pi):
....: p += plot(sin(x + phi), (x, -7, 7), rgbcolor = hue(phi))
sage: p
Graphics object consisting of 20 graphics primitives
INPUT:
• h - a number; the color’s hue
• s - a number (default: 1); the color’s saturation
sage: hue(0.6)
(0.0, 0.40000000000000036, 1.0)
sage: from sage.plot.colors import royalblue
sage: royalblue
RGB color (0.2549019607843137, 0.4117647058823529, 0.8823529411764706)
sage: hue(*royalblue.hsv())
(0.2549019607843137, 0.4117647058823529, 0.8823529411764706)
sage: hue(.5, .5, .5)
(0.25, 0.5, 0.5)
Note: The HSV to RGB coordinate transformation itself is given in the source code for the Python library’s
colorsys module:
sage.plot.colors.mod_one(x)
Reduce a number modulo 1.
INPUT:
• x - an instance of Integer, int, RealNumber, etc.; the number to reduce
OUTPUT:
• a float
EXAMPLES:
sage.plot.colors.rainbow(n, format=’hex’)
Returns a list of colors sampled at equal intervals over the spectrum, from Hue-Saturation-Value (HSV) coor-
dinates (0, 1, 1) to (1, 1, 1). This range is red at the extremes, but it covers orange, yellow, green, cyan, blue,
violet, and many other hues in between. This function is particularly useful for representing vertex partitions on
graphs.
INPUT:
• n - a number; the length of the list
• format - a string (default: ‘hex’); the output format for each color in the list; the other choice is ‘rgbtuple’
OUTPUT:
AUTHORS:
• Robert L. Miller
• Karl-Dieter Crisman (directly use hsv_to_rgb() for hues)
sage.plot.colors.rgbcolor(c, space=’rgb’)
Convert a color (string, tuple, list, or Color) to a mod-one reduced (see mod_one()) valid Red-Green-Blue
(RGB) tuple. The returned tuple is also a valid matplotlib RGB color.
INPUT:
• c - a Color instance, string (name or HTML hex), 3-tuple, or 3-list; the color to convert
• space - a string (default: ‘rgb’); the color space coordinate system (other choices are ‘hsl’, ‘hls’, and
‘hsv’) in which to interpret a 3-tuple or 3-list
OUTPUT:
• a RGB 3-tuple of floats in the interval [0.0, 1.0]
EXAMPLES:
sage.plot.colors.to_mpl_color(c, space=’rgb’)
Convert a color (string, tuple, list, or Color) to a mod-one reduced (see mod_one()) valid Red-Green-Blue
(RGB) tuple. The returned tuple is also a valid matplotlib RGB color.
INPUT:
• c - a Color instance, string (name or HTML hex), 3-tuple, or 3-list; the color to convert
• space - a string (default: ‘rgb’); the color space coordinate system (other choices are ‘hsl’, ‘hls’, and
‘hsv’) in which to interpret a 3-tuple or 3-list
OUTPUT:
• a RGB 3-tuple of floats in the interval [0.0, 1.0]
EXAMPLES:
Animations are generated from a list (or other iterable) of graphics objects. Images are produced by calling the
save_image method on each input object, creating a sequence of PNG files. These are then assembled to various
target formats using different tools. In particular, the convert program from ImageMagick can be used to generate
an animated GIF file. FFmpeg (with the command line program ffmpeg) provides support for various video formats,
but also an alternative method of generating animated GIFs. For browsers which support it, APNG can be used as
another alternative which works without any extra dependencies.
Warning: Note that ImageMagick and FFmpeg are not included with Sage, and must be installed by the user. On
unix systems, type which convert at a command prompt to see if convert (part of the ImageMagick suite)
is installed. If it is, you will be given its location. Similarly, you can check for ffmpeg with which ffmpeg.
See the websites of ImageMagick or FFmpeg for installation instructions.
EXAMPLES:
The sine function:
sage: a = animate(sines)
sage: a # optional -- ImageMagick
Animation with 5 frames
sage: a.show() # optional -- ImageMagick
sage: f = tmp_filename(ext='.gif')
sage: a.save(filename=f, use_ffmpeg=True) # optional -- ffmpeg
Animate as an APNG:
sage: E = animate((graphics_array([[ellipse((0,0),a,b,angle=t,xmin=-3,
˓→xmax=3)+circle((0,0),3,color='blue') for a in range(1,3)] for b in range(2,4)]) for
˓→t in sxrange(0,pi/4,.15)))
sage: str(E) # animations produced from a generator do not have a known length
'Animation with unknown number of frames'
sage: E.show() # optional -- ImageMagick
Animations of 3d objects:
sage: var('s,t')
(s, t)
sage: def sphere_and_plane(x):
....: return sphere((0,0,0),1,color='red',opacity=.5)+parametric_plot3d([t,x,s],
˓→(s,-1,1),(t,-1,1),color='green',opacity=.7)
If the input objects do not have a save_image method, then the animation object attempts to make an image by
calling its internal method sage.plot.animate.Animation.make_image(). This is illustrated by the fol-
lowing example:
sage: t = var('t')
sage: a = animate((sin(c*pi*t) for c in sxrange(1,2,.2)))
sage: a.show() # optional -- ImageMagick
AUTHORS:
• William Stein
• John Palmieri
• Niles Johnson (2013-12): Expand to animate more graphics objects
• Martin von Gagern (2014-12): Added APNG support
REFERENCES:
• ImageMagick
• FFmpeg
• APNG
• browsers which support it
class sage.plot.animate.APngAssembler(out, num_frames, num_plays=0, delay=200, de-
lay_denominator=100)
Bases: object
Builds an APNG (Animated PNG) from a sequence of PNG files. This is used by the sage.plot.animate.
Animation.apng() method.
This code is quite simple; it does little more than copying chunks from input PNG files to the output file. There
is no optimization involved. This does not depend on external programs or libraries.
INPUT:
• out – a file opened for binary writing to which the data will be written
• num_frames – the number of frames in the animation
• num_plays – how often to iterate, 0 means infinitely
• delay – numerator of the delay fraction in seconds
• delay_denominator – denominator of the delay in seconds
EXAMPLES:
REFERENCES:
• APNG
add_frame(pngfile, delay=None, delay_denominator=None)
Adds a single frame to the APNG file.
INPUT:
• pngfile – file name of the PNG file with data for this frame
• delay – numerator of the delay fraction in seconds
• delay_denominator – denominator of the delay in seconds
If the delay is not specified, the default from the constructor applies.
set_default(pngfile)
Adds a default image for the APNG file.
This image is used as a fallback in case some application does not understand the APNG format. This
method must be called prior to any calls to the add_frame method, if it is called at all. If it is not called,
then the first frame of the animation will be the default.
INPUT:
• pngfile – file name of the PNG file with data for the default image
class sage.plot.animate.Animation(v=None, **kwds)
Bases: sage.misc.fast_methods.WithEqualityById, sage.structure.sage_object.
SageObject
Return an animation of a sequence of plots of objects.
INPUT:
• v - iterable of Sage objects. These should preferably be graphics objects, but if they aren’t then
make_image() is called on them.
• xmin, xmax, ymin, ymax - the ranges of the x and y axes.
• **kwds - all additional inputs are passed onto the rendering command. E.g., use figsize to adjust the
resolution and aspect ratio.
EXAMPLES:
The show() method takes arguments to specify the delay between frames (measured in hundredths of a second,
default value 20) and the number of iterations (default value 0, which means to iterate forever). To iterate 4 times
with half a second between each frame:
....: v.append(L)
sage: a = animate(v, xmin=0, ymin=0)
sage: a.show() # optional -- ImageMagick
sage: show(L)
• show_path - boolean (default: False); if True, print the path to the saved file
• output_format - string (default: None); format and suffix to use for the video. This may be ‘mpg’,
‘mpeg’, ‘avi’, ‘gif’, or any other format that ffmpeg can handle. If this is None and the user specifies
savefile with a suffix, say savefile='animation.avi', try to determine the format (‘avi’
in this case) from that file name. If no file is specified or if the suffix cannot be determined, ‘mpg’ is
used.
• ffmpeg_options - string (default: ‘’); this string is passed directly to ffmpeg.
• delay - integer (default: None); delay in hundredths of a second between frames. The framerate is
100/delay. This is not supported for mpeg files: for mpegs, the frame rate is always 25 fps.
• iterations - integer (default: 0); number of iterations of animation. If 0, loop forever. This is
only supported for animated gif output and requires ffmpeg version 0.9 or later. For older versions,
set iterations=None.
• pix_fmt - string (default: ‘rgb24’); used only for gif output. Different values such as ‘rgb8’ or
‘pal8’ may be necessary depending on how ffmpeg was installed. Set pix_fmt=None to disable
this option.
If savefile is not specified: in notebook mode, display the animation; otherwise, save it to a default file
name. Use sage.misc.misc.set_verbose() with level=1 to see additional output.
EXAMPLES:
Note: If ffmpeg is not installed, you will get an error message like this:
• show_path - boolean (default: False); if True, print the path to the saved file
• use_ffmpeg - boolean (default: False); if True, use ‘ffmpeg’ by default instead of ‘convert’.
If savefile is not specified: in notebook mode, display the animation; otherwise, save it to a default file
name.
EXAMPLES:
Note: If neither ffmpeg nor ImageMagick is installed, you will get an error message like this:
REFERENCES:
• ImageMagick
• FFmpeg
graphics_array(ncols=3)
Return a sage.plot.graphics.GraphicsArray with plots of the frames of this animation, using
the given number of columns. The frames must be acceptable inputs for sage.plot.graphics.
GraphicsArray.
EXAMPLES:
sage: E = EllipticCurve('37a')
sage: v = [E.change_ring(GF(p)).plot(pointsize=30) for p in [97, 101, 103,
˓→107]]
Specify different arrangement of array and save it with a given file name:
sage: t = var('t')
sage: b = animate((plot(sin(c*pi*t)) for c in sxrange(1,2,.2)))
sage: g = b.graphics_array()
sage: g
Graphics Array of size 2 x 3
sage: t = var('t')
sage: x = lambda t: cos(t)
sage: y = lambda n,t: sin(t)/n
sage: B = MyAnimation([([x(t), y(i+1,t)],(t,0,1), {'color':Color((1,0,i/4)),
˓→'aspect_ratio':1, 'ymax':1}) for i in range(4)])
sage: d = B.png()
sage: v = os.listdir(d); v.sort(); v
['00000000.png', '00000001.png', '00000002.png', '00000003.png']
sage: B.show() # not tested
png(dir=None)
Render PNG images of the frames in this animation, saving them in dir. Return the absolute path to that
directory. If the frames have been previously rendered and dir is None, just return the directory in which
they are stored.
When dir is other than None, force re-rendering of frames.
INPUT:
• dir – Directory in which to store frames. Default None; in this case, a temporary directory will be
created for storing the frames.
EXAMPLES:
• format - (default: gif) format to use for output. Currently supported formats are: gif, ogg, webm,
mp4, flash, matroska, avi, wmv, quicktime.
OUTPUT:
This method does not return anything. Use save() if you want to save the figure as an image.
Note: Currently this is done using an animated gif, though this could change in the future. This requires
that either ffmpeg or the ImageMagick suite (in particular, the convert command) is installed.
The preceding will loop the animation forever. If you want to show only three iterations instead:
You can also make use of the HTML5 video element in the Sage Notebook:
Note: If you don’t have ffmpeg or ImageMagick installed, you will get an error message like this:
sage.plot.animate.animate(frames, **kwds)
Animate a list of frames by creating a sage.plot.animate.Animation object.
EXAMPLES:
sage: t = var('t')
sage: a = animate((cos(c*pi*t) for c in sxrange(1,2,.2)))
sage: a.show() # optional -- ImageMagick
TWO
169
Sage Reference Manual: 2D Graphics, Release 8.8
-4 -2 2 4
-2
-4
-4 -2 2 4
-2
-4
10
-10 -5 5 10
-5
-10
10
-10 -5 5 10
-5
-10
-3 -2 -1 1 2 3
-1
-2
-3
Here is the identity, useful for seeing what values map to what colors:
-3 -2 -1 1 2 3
-1
-2
-3
The Riemann Zeta function:
Extra options will get passed on to show(), as long as they are valid:
sage.plot.complex_plot.complex_to_rgb(z_values)
INPUT:
• z_values – A grid of complex numbers, as a list of lists
30
20
10
-10
-20
-30
OUTPUT:
An 𝑁 × 𝑀 × 3 floating point Numpy array X, where X[i,j] is an (r,g,b) tuple.
EXAMPLES:
get_minmax_data()
Returns a dictionary with the bounding box data.
EXAMPLES:
– label_fmt – a format string (default: “%1.2f”), this is used to get the label text from the level. This
can also be a dictionary with the contour levels as keys and corresponding text string labels as values.
It can also be any callable which returns a string when called with a numeric contour level.
• colorbar – boolean (default: False) Show a colorbar or not.
The following options are to adjust the style and placement of colorbars. They have no effect if a colorbar
is not shown.
– colorbar_orientation – string (default: ‘vertical’), controls placement of the colorbar, can be
either ‘vertical’ or ‘horizontal’
– colorbar_format – a format string, this is used to format the colorbar labels.
– colorbar_spacing – string (default: ‘proportional’). If ‘proportional’, make the contour divi-
sions proportional to values. If ‘uniform’, space the colorbar divisions uniformly, without regard for
numeric values.
• legend_label – the label for this item in the legend
• region - (default: None) If region is given, it must be a function of two variables. Only segments of
the surface where region(x,y) returns a number >0 will be included in the plot.
EXAMPLES:
Here we plot a simple function of two variables. Note that since the input function is an expression, we need to
explicitly declare the variables in 3-tuples for the range:
Some elliptic curves, but with symbolic endpoints. In the first example, the plot is rotated 90 degrees because
we switch the variables 𝑥, 𝑦:
-1
-2
-3
-4
-4 -3 -2 -1 0 1 2 3 4
-2
-4
-10 -8 -6 -4 -2 0 2 4
-1
-2
-3
-4
-4 -3 -2 -1 0 1 2 3 4
-1
-2
-3
-3 -2 -1 0 1 2 3
-1
-2
-3
-3 -2 -1 0 1 2 3
1.5
0.5
-0.5
-1
-1.5
-2
-2 -1.5 -1 -0.5 0 0.5 1 1.5 2
sage: contour_plot(f, (-2,2), (-2,2), contours=2, cmap=[(1,0,0), (0,1,0), (0,0,
˓→1)])
1.5
0.5
-0.5
-1
-1.5
-2
-2 -1.5 -1 -0.5 0 0.5 1 1.5 2
1.5
0.5
-0.5
-1
-1.5
-2
-2 -1.5 -1 -0.5 0 0.5 1 1.5 2
1.5
0.5
-0.5
-1
-1.5
-2
-2 -1.5 -1 -0.5 0 0.5 1 1.5 2
-1
-2
-3
-4 -2 0 2 4
1.5
0.5
-0.5
-1
-1.5
-2
-2 -1.5 -1 -0.5 0 0.5 1 1.5 2
1.5
0.5
-0.5
-1
-1.5
-2
-2 -1.5 -1 -0.5 0 0.5 1 1.5 2
sage: P = contour_plot(x^2 - y^2, (x,-3,3), (y,-3,3),
....: contours=[0,1,2,3,4], linewidths=[1,5],
....: linestyles=['solid','dashed'], fill=False)
sage: P
Graphics object consisting of 1 graphics primitive
-1
-2
-3
-3 -2 -1 0 1 2 3
-1
-2
-3
-3 -2 -1 0 1 2 3
-1
-2
-3
-3 -2 -1 0 1 2 3
3 40.00
0
0.0
1
-10.00
0
20.00
-30.00
-1
-20.00
-2
30.00
40.00
-3 10.00
-3 -2 -1 0 1 2 3
sage: P=contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi),
....: fill=False, cmap='hsv',
....: labels=True, label_fmt="%1.0f",
....: label_colors='black')
sage: P
Graphics object consisting of 1 graphics primitive
0
40
1
20
30
-1
-30
-2
-20
-10
40
-3 10
-3 -2 -1 0 1 2 3
m
diu
me
1
-1
hi
-2
low
-3
-3 -2 -1 0 1 2 3
z = 0.0
0
-1
z= −
4.0
-2 z=
4.0
-3
-3 -2 -1 0 1 2 3
sage: P = contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi),
....: fill=False, cmap='hsv', labels=True,
....: label_fontsize=18)
sage: P
Graphics object consisting of 1 graphics primitive
30.00
2
10.00
-30.00
0
-10.00
-1
20.00
-20.00
0.0
-2
0
-3
-3 -2 -1 0 1 2 3
3
40.00
0
0.0
1
-10.00
0
20.00
-30.00
-1 -20.00
-2
30.00
40.00
-3 10.00
-3 -2 -1 0 1 2 3
3
40.00
0
0.0
1
-10.00
0
20.00
-30.00
-1 -20.00
-2
30.00
40.00
-3 10.00
-3 -2 -1 0 1 2 3
2
0 5.00 6.0
6.0 0
1.5 0 0
5.0 3.0 2.00
1
0.5
-0.5
-1 1.00
4.0 0
-1.5
0 5.0
6.0 0
0 5.00 6.0
-2
-2 -1.5 -1 -0.5 0 0.5 1 1.5 2
We can add a colorbar as well:
3 20.0
17.5
2
15.0
1
12.5
0 10.0
7.5
-1
5.0
-2
2.5
-3 0.0
-3 -2 -1 0 1 2 3
-1
-2
-3
-3 -2 -1 0 1 2 3
3
4
-1
-2 1
2
-3
-3 -2 -1 0 1 2 3
3
4
0 1
-1
-2
2
-3
-3 -2 -1 0 1 2 3
3
6.000
0 3.000
-1 2.000
-2
0.000
-3
-3 -2 -1 0 1 2 3
3
6
2
3.00
0 3
-1 2.0 2
0
-2 6.00
0
-3
-3 -2 -1 0 1 2 3
sage: contour_plot(f, (x,-3,3), (y,-3,3), cmap='winter',
....: contours=20, fill=False, colorbar=True)
Graphics object consisting of 1 graphics primitive
Extra options will get passed on to show(), as long as they are valid:
3 17
15
2
13
1
11
0 9
7
-1
5
-2
3
-3 1
-3 -2 -1 0 1 2 3
0.5
-0.5
-1
-1 -0.5 0 0.5 1
2.5
1.5
0.5
0
0 0.5 1 1.5 2 2.5 3
1.5
0.5
-0.5
-1
-1.5
-2
-2 -1.5 -1 -0.5 0 0.5 1 1.5 2
Note that with fill=False and grayscale contours, there is the possibility of confusion between the contours
and the axes, so use fill=False together with axes=True with caution:
sage.plot.contour_plot.equify(f )
Returns the equation rewritten as a symbolic function to give negative values when True, positive when False.
EXAMPLES:
-1
-2
-3
-3 -2 -1 0 1 2 3
-1
-2
-3
-3 -2 -1 0 1 2 3
We can do the same thing, but using a callable function so we don’t need to explicitly define the variables in the
ranges. We also fill the inside:
Again the same circle but this time with a dashdot border:
-3 -2 -1 1 2 3
-1
-2
-3
-1
-2
-3
-3 -2 -1 0 1 2 3
-1
-2
-3
-3 -2 -1 0 1 2 3
-3 -2 -1 1 2 3
-1
-2
-3
You can also plot an equation:
Here is a beautiful (and long) example which also tests that all colors work with this:
-1
-2
-3
-3 -2 -1 0 1 2 3
-1
-2
-3
-3 -2 -1 0 1 2 3
-3 -2 -1 1 2 3
-1
-2
-3
sage: G = Graphics()
sage: counter = 0
sage: for col in colors.keys(): # long time
....: G += implicit_plot(x^2 + y^2 == 1 + counter*.1, (x,-4,4),(y,-4,4),
˓→color=col)
....: counter += 1
sage: G # long time
Graphics object consisting of 148 graphics primitives
-1
-2
-3
-4
-4 -3 -2 -1 0 1 2 3 4
We can define a level-𝑛 approximation of the boundary of the Mandelbrot set:
sage: def mandel(n):
....: c = polygen(CDF, 'c')
....: z = 0
....: for i in range(n):
....: z = z*z + c
....: def f(x,y):
....: val = z(CDF(x, y))
....: return val.norm() - 4
....: return f
-1
-2
-3
-3 -2 -1 0 1 2 3
1.5
0.5
-0.5
-1
-1.5
-2 -1.5 -1 -0.5 0 0.5 1
The seventh-level approximation is a degree 64 polynomial, and implicit_plot does a pretty good job on
this part of the curve. (plot_points=200 looks even better, but it takes over a second.)
When making a filled implicit plot using a python function rather than a symbolic expression the user should
increase the number of plot points to avoid artifacts:
-0.9
-0.95
-1
-1.05
-1.1
-1.15
-0.3 -0.25 -0.2 -0.15 -0.1 -0.05 0 0.05
-3 -2 -1 1 2 3
-1
-2
-3
102
101
100
100 101 102
-3 -2 -1 1 2 3
-1
-2
-3
1.5
0.5
-1
-1.5
-2
An even more complicated plot, with dashed borders:
sage: region_plot(sin(x) * sin(y) >= 1/4, (x,-10,10), (y,-10,10),
....: incol='yellow', bordercol='black',
....: borderstyle='dashed', plot_points=250)
Graphics object consisting of 2 graphics primitives
A plot with more than one condition (all conditions must be true for the statement to be true):
sage: region_plot([x^2 + y^2 < 1, x < y], (x,-2,2), (y,-2,2))
Graphics object consisting of 1 graphics primitive
10
-10 -5 5 10
-5
-10
0.5
-1 -0.5 0.5 1
-0.5
-1
1.5
0.5
-1
-1.5
-2
1.5
0.5
-1
-1.5
-2
To get plots where only one condition needs to be true, use a function. Using lambda functions, we definitely
need the extra plot_points:
1.5
0.5
-1
-1.5
-2
The first quadrant of the unit circle:
sage: region_plot([y > 0, x > 0, x^2 + y^2 < 1], (x,-1.1,1.1), (y,-1.1,1.1), plot_
˓→points=400)
0.5
-1 -0.5 0.5 1
-0.5
-1
-3 -2 -1 1 2
-1
-2
-3
-3 -2 -1 1 2
-1
-2
-3
1.5
0.5
-1
-1.5
-2
The first variable range corresponds to the horizontal axis and the second variable range corresponds to the
vertical axis:
sage: region_plot(s>0,(s,-2,2),(t,-2,2))
Graphics object consisting of 1 graphics primitive
1.5
0.5
-1
-1.5
-2
1.5
0.5
-1
-1.5
-2
101
100
100 101
get_minmax_data()
Returns a dictionary with the bounding box data.
EXAMPLES:
• cmap – a colormap (default: 'gray'), the name of a predefined colormap, a list of colors or an instance
of a matplotlib Colormap. Type: import matplotlib.cm; matplotlib.cm.datad.keys()
for available colormap names.
• interpolation – string (default: 'catrom'), the interpolation method to use: 'bilinear',
'bicubic', 'spline16', 'spline36', 'quadric', 'gaussian', 'sinc', 'bessel',
'mitchell', 'lanczos', 'catrom', 'hermite', 'hanning', 'hamming', 'kaiser'
EXAMPLES:
Here we plot a simple function of two variables. Note that since the input function is an expression, we need to
explicitly declare the variables in 3-tuples for the range:
1.5
0.5
-1
-1.5
-2
Here we change the ranges and add some options; note that here f is callable (has variables declared), so we
can use 2-tuple ranges:
-10 -8 -6 -4 -2 2 4
-2
-4
-4 -3 -2 -1 1 2 3 4
-1
-2
-3
-4
This should show a “spotlight” right on the origin:
Some elliptic curves, but with symbolic endpoints. In the first example, the plot is rotated 90 degrees because
we switch the variables 𝑥, 𝑦:
Extra options will get passed on to show(), as long as they are valid:
10
-10 -5 5 10
-5
-10
-3 -2 -1 1 2 3
-1
-2
-3
-3 -2 -1 1 2 3
-1
-2
-3
10
2 4 6 8 10
sage: d['xmin']
10.0
sage: d['ymin']
10.0
0
0 1 2 3 4 5
-1
-2
-3
-3 -2 -1 0 1 2 3
1.5
0.5
-0.5
-1
-1.5
-2
-2 -1.5 -1 -0.5 0 0.5 1 1.5 2
𝑥 and 𝑦, take (𝑓 (𝑥, 𝑦), 𝑔(𝑥, 𝑦))) and plots vector arrows of the function over the specified ranges, with xrange
being of xvar between xmin and xmax, and yrange similarly (see below).
plot_vector_field((f,g), (xvar,xmin,xmax), (yvar,ymin,ymax))
EXAMPLES:
Plot some vector fields involving sin and cos:
-1
-2
-3
-3 -2 -1 0 1 2 3
sage: plot_vector_field((y,(cos(x)-2) * sin(x)), (x,-pi,pi), (y,-pi,pi))
Graphics object consisting of 1 graphics primitive
-1
-2
-3
-3 -2 -1 0 1 2 3
1.5
0.5
-0.5
-1
-1.5
-2
-2 -1.5 -1 -0.5 0 0.5 1 1.5 2
-1
-2
-3
-3 -2 -1 0 1 2 3
We ignore function values that are infinite or NaN:
Extra options will get passed on to show(), as long as they are valid:
10
-5
-10
-10 -5 0 5 10
10
-5
-10
-10 -5 0 5 10
1.5
0.5
-0.5
-1
-1.5
-2
-2 0 2 4 6 8 10
sage: d['xmin']
10.0
sage: d['ymin']
10.0
Similarly, if given one function 𝑓 (𝑥, 𝑦), then this function plots streamlines in the slope field 𝑑𝑦/𝑑𝑥 = 𝑓 (𝑥, 𝑦)
over the specified ranges as given above.
PLOT OPTIONS:
• plot_points – (default: 200) the minimal number of plot points
• density – float (default: 1.); controls the closeness of streamlines
• start_points – (optional) list of coordinates of starting points for the streamlines; coordinate pairs
can be tuples or lists
EXAMPLES:
Plot some vector fields involving sin and cos:
-1
-2
-3
-3 -2 -1 0 1 2 3
-1
-2
-3
-3 -2 -1 0 1 2 3
-1
-2
-3
-3 -2 -1 0 1 2 3
10
-5
-10
-10 -5 0 5 10
Extra options will get passed on to show(), as long as they are valid:
sage: streamline_plot((x, y), (x,-2,2), (y,-2,2), xmax=10)
Graphics object consisting of 1 graphics primitive
sage: streamline_plot((x, y), (x,-2,2), (y,-2,2)).show(xmax=10) # These are
˓→equivalent
1.5
0.5
-0.5
-1
-1.5
-2
-2 0 2 4 6 8 10
-1
-2
-3
-3 -2 -1 0 1 2 3
-1
-2
-3
-3 -2 -1 0 1 2 3
Note: Streamlines currently pass close to start_points but do not necessarily pass directly through them.
That is part of the behavior of matplotlib, not an error on your part.
get_minmax_data()
Returns a dictionary with the bounding box data.
EXAMPLES:
sage: s = scatter_plot([[0,1],[2,4],[3.2,6]])
sage: d = s.get_minmax_data()
sage: d['xmin']
0.0
sage: d['ymin']
1.0
Extra options will get passed on to show(), as long as they are valid:
We pass in many options and get something that looks like “Space Invaders”:
sage: v = [(i,sin(i)) for i in range(5,20)]
sage: plot_step_function(v, vertical_lines=False, thickness=30, rgbcolor='purple',
˓→ axes=False)
2.8 Histograms
get_minmax_data()
Get minimum and maximum horizontal and vertical ranges for the Histogram object.
EXAMPLES:
sage: H = histogram([10,3,5], density=True); h = H[0]
sage: h.get_minmax_data() # rel tol 1e-15
{'xmax': 10.0, 'xmin': 3.0, 'ymax': 0.4761904761904765, 'ymin': 0}
sage: G = histogram([random() for _ in range(500)]); g = G[0]
sage: g.get_minmax_data() # random output
{'xmax': 0.99729312925213209, 'xmin': 0.00013024562219410285, 'ymax': 61,
˓→'ymin': 0}
(continues on next page)
Note: The weights option works only with a single list. List of lists representing multiple data are not
supported.
EXAMPLES:
A very basic histogram for four data points:
We can see how the histogram compares to various distributions. Note the use of the density keyword to
guarantee the plot looks like the probability density function:
sage: nv = normalvariate
sage: H = histogram([nv(0,1) for _ in range(1000)], bins=20, density=True,
˓→range=[-5,5])
There are many options one can use with histograms. Some of these control the presentation of the data, even if
it is boring:
get_minmax_data()
Returns a dictionary with the bounding box data.
EXAMPLES:
sage: b = bar_chart([-2.3,5,-6,12])
sage: d = b.get_minmax_data()
sage: d['xmin']
0
sage: d['xmax']
4
sage: bar_chart([1,2,3,4])
Graphics object consisting of 1 graphics primitive
Extra options will get passed on to show(), as long as they are valid:
THREE
sage: G = graphs.WheelGraph(15)
sage: P = G.plot()
sage: P.show() # long time
1
2 14
3 13
4 12
5 11
6 10
7 9
8
If you create a graph in Sage using the Graph command, then plot that graph, the positioning of nodes is determined
277
Sage Reference Manual: 2D Graphics, Release 8.8
using the spring-layout algorithm. For the special graph constructors, which you get using graphs.[tab], the
positions are preset. For example, consider the Petersen graph with default node positioning vs. the Petersen graph
constructed by this database:
4 9
3
6
0 8 7
1
2
5
sage: petersen_database = graphs.PetersenGraph()
sage: petersen_database.show() # long time
For all the constructors in this database (except some random graphs), the position dictionary is filled in, instead of
using the spring-layout algorithm.
Plot options
Here is the list of options accepted by plot() and the constructor of GraphPlot. Those two functions also accept
all options of sage.plot.graphics.Graphics.show().
1 4
6 9
7 8
2 3
partition A partition of the vertex set. If specified, plot will show each cell in a different
color. vertex_colors takes precedence.
dist The distance between multiedges.
vertex_labels Whether or not to draw vertex labels.
edge_color The default color for edges not listed in edge_colors.
spring Use spring layout to finalize the current layout.
pos The position dictionary of vertices
loop_size The radius of the smallest loop.
color_by_label Whether to color the edges according to their labels. This also accepts a function
or dictionary mapping labels to colors.
iterations The number of times to execute the spring layout algorithm.
talk Whether to display the vertices in talk mode (larger and white).
edge_labels Whether or not to draw edge labels.
vertex_size The size to draw the vertices.
edge_thickness The thickness of the edges.
dim The dimension of the layout – 2 or 3.
edge_style The linestyle of the edges. It should be one of “solid”, “dashed”, “dotted”,
dashdot”, or “-“, “–”, “:”, “-.”, respectively.
layout A layout algorithm – one of : “acyclic”, “circular” (plots the graph with vertices
evenly distributed on a circle), “ranked”, “graphviz”, “planar”, “spring” (tradi-
tional spring layout, using the graph’s current positions as initial positions), or
“tree” (the tree will be plotted in levels, depending on minimum distance for the
root).
vertex_shape The shape to draw the vertices. Currently unavailable for Multi-edged Di-
Graphs.
vertex_colors Dictionary of vertex coloring : each key is a color recognizable by matplotlib,
and each corresponding entry is a list of vertices.
by_component Whether to do the spring layout by connected component – a boolean.
heights A dictionary mapping heights to the list of vertices at this height.
graph_border Whether or not to draw a frame around the graph.
max_dist The max distance range to allow multiedges.
prog Which graphviz layout program to use – one of “circo”, “dot”, “fdp”, “neato”,
or “twopi”.
edge_colors a dictionary specifying edge colors: each key is a color recognized by mat-
plotlib, and each entry is a list of edges.
vertex_color Default color for vertices not listed in vertex_colors dictionary.
tree_orientation The direction of tree branches – ‘up’, ‘down’, ‘left’ or ‘right’.
save_pos Whether or not to save the computed position for the graph.
tree_root A vertex designation for drawing trees. A vertex of the tree to be used as the
root for the layout='tree' option. If no root is specified, then one is chosen
close to the center of the tree. Ignored unless layout='tree'
edge_labels_background The color of the background of the edge labels
Default options
This module defines two dictionaries containing default options for the plot() and show() methods. These two dic-
tionaries are sage.graphs.graph_plot.DEFAULT_PLOT_OPTIONS and sage.graphs.graph_plot.
DEFAULT_SHOW_OPTIONS, respectively.
Obviously, these values are overruled when arguments are given explicitly.
Here is how to define the default size of a graph drawing to be [6,6]. The first two calls to show() use this option,
while the third does not (a value for figsize is explicitly given):
We can now reset the default to its initial value, and now display graphs as previously:
sage: sage.graphs.graph_plot.DEFAULT_SHOW_OPTIONS['figsize'] = [4,4]
sage: graphs.PetersenGraph().show() # long time
sage: graphs.ChvatalGraph().show() # long time
Note:
• While DEFAULT_PLOT_OPTIONS affects both G.show() and G.plot(), settings from
DEFAULT_SHOW_OPTIONS only affects G.show().
• In order to define a default value permanently, you can add a couple of lines to Sage’s startup scripts. Example:
sage: import sage.graphs.graph_plot
sage: sage.graphs.graph_plot.DEFAULT_SHOW_OPTIONS['figsize'] = [4,4]
layout_tree(root, orientation)
Compute a nice layout of a tree.
INPUT:
• root – the root vertex.
• orientation – whether to place the root at the top or at the bottom:
– orientation="down" – children are placed below their parent
– orientation="top" – children are placed above their parent
EXAMPLES:
sage: from sage.graphs.graph_plot import GraphPlot
sage: G = graphs.HoffmanSingletonGraph()
sage: T = Graph()
sage: T.add_edges(G.min_spanning_tree(starting_vertex=0))
sage: T.show(layout='tree', tree_root=0) # indirect doctest
plot(**kwds)
Return a graphics object representing the (di)graph.
INPUT:
The options accepted by this method are to be found in the documentation of the sage.graphs.
graph_plot module, and the show() method.
Note: See the module's documentation for information on default values of this method.
1 4
6 9
7 8
2 3
Here are some more common graphs with typical options:
sage: C = graphs.CubeGraph(8)
sage: P = C.graphplot(vertex_labels=False, vertex_size=0, graph_border=True)
sage: P.show()
sage: G = graphs.HeawoodGraph().copy(sparse=True)
sage: for u,v,l in G.edges():
....: G.set_edge_label(u,v,'(' + str(u) + ',' + str(v) + ')')
sage: G.graphplot(edge_labels=True).show()
(0,1) 0 (0,13) 13
1
(1,2) (12,13)
2 12
4 (2,7) 10
(6,11)
(4,5) (4,9) (9,10)
5 9
(5,6) (8,9)
6 (6,7) (7,8) 8
7
1 (0,1) 0 (0,19) 19
(1,2) (18,19)
2 (3,19) 18
(2,3) (17,18)
3 17
(3,4) (4,17) (16,17)
4 16
(2,6)
(4,5) (15,16)
(1,8)
5 (0,10)
(5,15) 15
(11,18)
(5,6) (14,15)
(12,16)
6 14
(6,7) (7,14) (13,14)
7 13
(7,8) (12,13)
8 (9,13) 12
(8,9) (11,12)
9 (9,10) 10 (10,11) 11
With the partition option, we can separate out same-color groups of vertices:
sage: D = graphs.DodecahedralGraph()
sage: Pi = [[6,5,15,14,7],[16,13,8,2,4],[12,17,9,3,1],[0,19,18,10,11]]
sage: D.show(partition=Pi)
10
9 11
1 19
8 13 12 18
14 16
7 17
15
6 5 4
2 3
1 4
6 9
7 8
2 3
sage: D = DiGraph({0:[0,1], 1:[2], 2:[3]}, loops=True)
sage: D.show()
sage: D.show(edge_colors={(0,1,0):[(0,1,None),(1,2,None)],(0,0,0):[(2,3,
˓→None)]})
More options:
sage: pos = {0:[0.0, 1.5], 1:[-0.8, 0.3], 2:[-0.6, -0.8],
....: 3:[0.6, -0.8], 4:[0.8, 0.3]}
sage: g = Graph({0:[1], 1:[2], 2:[3], 3:[4], 4:[0]})
sage: g.graphplot(pos=pos, layout='spring', iterations=0).plot()
Graphics object consisting of 11 graphics primitives
sage: G = Graph()
sage: P = G.graphplot().plot()
sage: P.axes()
False
sage: G = DiGraph()
sage: P = G.graphplot().plot()
sage: P.axes()
(continues on next page)
5
3
0
sage: T = list(graphs.trees(7))
sage: t = T[3]
sage: t.graphplot(heights={0:[0], 1:[4,5,1], 2:[2], 3:[3,6]}).plot()
Graphics object consisting of 14 graphics primitives
sage: t.set_edge_label(0,1,-7)
sage: t.set_edge_label(0,5,3)
sage: t.set_edge_label(0,5,99)
sage: t.set_edge_label(1,2,1000)
sage: t.set_edge_label(3,2,'spam')
sage: t.set_edge_label(2,6,3/2)
sage: t.set_edge_label(0,4,66)
sage: t.graphplot(heights={0:[0], 1:[4,5,1], 2:[2], 3:[3,6]}, edge_
˓→labels=True).plot()
4 5
6
None
5
3
99
0
None
-7
1
1000
2
None
sage: T = list(graphs.trees(7))
sage: t = T[3]
sage: t.graphplot(layout='tree').show()
sage: t = DiGraph('JCC???@A??GO??CO??GO??')
sage: t.graphplot(layout='tree', tree_root=0, tree_orientation="up").show()
More examples:
5 1
6 4 3 2
4 8 1 6
7 2 5 10
3 9
1
2
5
a
4 a
b 3 a
b 2 a
b 1 a
b 0
b
-1
2
h
f fefdc f
0
a
b
The edge_style option may be provided in the short format too:
sage: g.graphplot(edge_labels=True, color_by_label=True, edge_style='--').
˓→plot()
set_edges(**edge_options)
Set the edge (or arrow) plotting parameters for the GraphPlot object.
This function is called by the constructor but can also be called to make updates to the vertex options of
an existing GraphPlot object. Note that the changes are cumulative.
EXAMPLES:
sage: g = Graph(loops=True, multiedges=True, sparse=True)
sage: g.add_edges([(0,0,'a'),(0,0,'b'),(0,1,'c'),(0,1,'d'),
....: (0,1,'e'),(0,1,'f'),(0,1,'f'),(2,1,'g'),(2,2,'h')])
sage: GP = g.graphplot(vertex_size=100, edge_labels=True, color_by_label=True,
(continues on next page)
f a
f b
e
f
d
c
f
h
sage: GP.set_edges(edge_color='black')
sage: GP.plot()
Graphics object consisting of 26 graphics primitives
sage: GP.set_edges(edge_color='black')
sage: GP.plot()
Graphics object consisting of 28 graphics primitives
set_pos()
0
a
f b
f
e
f
d
c
f
2
h
0
a
b f
d c
e f
f f
2
h
2
h
f f
ef
dc
f
0
a
b
The following illustrates the format of a position dictionary, but due to numerical noise we do not check
the values themselves:
sage: g.get_pos()
{0: (0.0, 1.0),
1: (-0.951..., 0.309...),
2: (-0.587..., -0.809...),
3: (0.587..., -0.809...),
4: (0.951..., 0.309...)}
sage: T = list(graphs.trees(7))
sage: t = T[3]
sage: t.plot(heights={0:[0], 1:[4,5,1], 2:[2], 3:[3,6]})
Graphics object consisting of 14 graphics primitives
0
4
2
set_vertices(**vertex_options)
0
a
b
f f e f
dc f
2
h
show(**kwds)
Show the (Di)Graph associated with this GraphPlot object.
INPUT:
This method accepts all parameters of sage.plot.graphics.Graphics.show().
0
a
b
f
f e f dc
f
2
h
Note:
• See the module's documentation for information on default values of this method.
• Any options not used by plot will be passed on to the show() method.
EXAMPLES:
sage: C = graphs.CubeGraph(8)
sage: P = C.graphplot(vertex_labels=False, vertex_size=0, graph_border=True)
sage: P.show()
• yrange - tuple of 2 floats indicating range for vertical direction (number of rows in the matrix)
• options - dict of valid plot options to pass to constructor
EXAMPLES:
Note this should normally be used indirectly via matrix_plot():
Extra options will get passed on to show(), as long as they are valid:
get_minmax_data()
Returns a dictionary with the bounding box data.
EXAMPLES:
sage: m = matrix_plot(matrix([[1,3,5,1],[2,4,5,6],[1,3,5,7]]))[0]
sage: list(sorted(m.get_minmax_data().items()))
[('xmax', 3.5), ('xmin', -0.5), ('ymax', -0.5), ('ymin', 2.5)]
The list of predefined color maps can be visualized in matplotlib’s documentation. You can also type
import matplotlib.cm; matplotlib.cm.datad.keys() to list their names.
• colorbar – boolean (default: False) Show a colorbar or not (dense matrices only).
The following options are used to adjust the style and placement of colorbars. They have no effect if a
colorbar is not shown.
– colorbar_orientation – string (default: ‘vertical’), controls placement of the colorbar, can be
either ‘vertical’ or ‘horizontal’
– colorbar_format – a format string, this is used to format the colorbar labels.
– colorbar_options – a dictionary of options for the matplotlib colorbar API. Documentation for
the matplotlib.colorbar module has details.
• norm - If None (default), the value range is scaled to the interval [0,1]. If ‘value’, then the actual value is
used with no scaling. A matplotlib.colors.Normalize instance may also passed.
• vmin - The minimum value (values below this are set to this value)
• vmax - The maximum value (values above this are set to this value)
• origin - If ‘upper’ (default), the first row of the matrix is on the top of the graph. If ‘lower’, the first row
is on the bottom of the graph.
• subdivisions - If True, plot the subdivisions of the matrix as lines.
• subdivision_boundaries - a list of lists in the form [row_subdivisions,
column_subdivisions], which specifies the row and column subdivisions to use. If not specified,
defaults to the matrix subdivisions
• subdivision_style - a dictionary of properties passed on to the line2d() command for plotting
subdivisions. If this is a two-element list or tuple, then it specifies the styles of row and column divisions,
respectively.
EXAMPLES:
A matrix over Z colored with different grey levels:
sage: matrix_plot(matrix([[1,3,5,1],[2,4,5,6],[1,3,5,7]]))
Graphics object consisting of 1 graphics primitive
Here we make a random matrix over R and use cmap='hsv' to color the matrix elements different RGB
colors:
By default, entries are scaled to the interval [0,1] before determining colors from the color map. That means the
two plots below are the same:
sage: P = matrix_plot(matrix(2,[1,1,3,3]))
sage: Q = matrix_plot(matrix(2,[2,2,3,3]))
sage: P; Q
Graphics object consisting of 1 graphics primitive
Graphics object consisting of 1 graphics primitive
However, we can specify which values scale to 0 or 1 with the vmin and vmax parameters (values outside the
range are clipped). The two plots below are now distinguished:
We can also specify a norm function of ‘value’, which means that there is no scaling performed:
sage: m=random_matrix(RR,10)
sage: m.subdivide([2,4],[6,8])
sage: matrix_plot(m, subdivisions=True, subdivision_style=dict(color='red',
˓→thickness=3))
You can also specify your own subdivisions and separate styles for row or column subdivisions:
sage: m=random_matrix(RR,10)
sage: matrix_plot(m, subdivisions=True, subdivision_boundaries=[[2,4],[6,8]],
˓→subdivision_style=[dict(color='red',thickness=3),dict(linestyle='--',
˓→thickness=6)])
Generally matrices are plotted with the (0,0) entry in the upper left. However, sometimes if we are plotting an
image, we’d like the (0,0) entry to be in the lower left. We can do that with the origin argument:
The length of a color bar and the length of the adjacent matrix plot dimension may be quite different. This
example shows how to adjust the length of the colorbar by passing a dictionary of options to the matplotlib
colorbar routines.
sage: matrix_plot(sparse)
Graphics object consisting of 1 graphics primitive
sage: A=random_matrix(ZZ,100000,density=.00001,sparse=True)
sage: matrix_plot(A,marker=',')
Graphics object consisting of 1 graphics primitive
As with dense matrices, sparse matrix entries are automatically converted to floating point numbers before
plotting. Thus the following works:
sage: b=random_matrix(GF(2),200,sparse=True,density=0.01)
sage: matrix_plot(b)
Graphics object consisting of 1 graphics primitive
sage: b=random_matrix(CDF,200,sparse=True,density=0.01)
sage: matrix_plot(b)
Traceback (most recent call last):
...
ValueError: can not convert entries to floating point numbers
To plot the absolute value of a complex matrix, use the apply_map method:
sage: b=random_matrix(CDF,200,sparse=True,density=0.01)
sage: matrix_plot(b.apply_map(abs))
Graphics object consisting of 1 graphics primitive
sage: matrix_plot([[1,3,5,1],[2,4,5,6],[1,3,5,7]])
Graphics object consisting of 1 graphics primitive
The title position is adjusted upwards if the origin keyword is set to "upper" (this is the default).:
sage: matrix_plot([1,2,3])
Traceback (most recent call last):
...
TypeError: mat must be a Matrix or a two dimensional array
Test that matrix plots have aspect ratio one (see trac ticket #15315):
FOUR
BASIC SHAPES
bezier_path()
Return self as a Bezier path.
This is needed to concatenate arcs, in order to create hyperbolic polygons.
EXAMPLES:
313
Sage Reference Manual: 2D Graphics, Release 8.8
get_minmax_data()
Return a dictionary with the bounding box data.
The bounding box is computed as minimal as possible.
EXAMPLES:
An example without angle:
plot3d()
sage.plot.arc.arc(center, r1, r2=None, angle=0.0, sector=(0.0, 6.283185307179586), rgb-
color=’blue’, thickness=1, zorder=5, aspect_ratio=1.0, alpha=1, linestyle=’solid’,
**options)
An arc (that is a portion of a circle or an ellipse)
Type arc.options to see all options.
INPUT:
• center - 2-tuple of real numbers - position of the center.
• r1, r2 - positive real numbers - radii of the ellipse. If only r1 is set, then the two radii are supposed to be
equal and this function returns an arc of circle.
• angle - real number - angle between the horizontal and the axis that corresponds to r1.
• sector - 2-tuple (default: (0,2*pi))- angles sector in which the arc will be drawn.
OPTIONS:
• alpha - float (default: 1) - transparency
• thickness - float (default: 1) - thickness of the arc
• color, rgbcolor - string or 2-tuple (default: ‘blue’) - the color of the arc
• linestyle - string (default: 'solid') - The style of the line, which is one of 'dashed', 'dotted',
'solid', 'dashdot', or '--', ':', '-', '-.', respectively.
EXAMPLES:
Plot an arc of circle centered at (0,0) with radius 1 in the sector (𝜋/4, 3 * 𝜋/4):
sage: A = arc((0,0,0), 1)
Traceback (most recent call last):
...
NotImplementedError
4.2 Arrows
get_minmax_data()
Returns a bounding box for this arrow.
EXAMPLES:
sage: A = arrow((0,0),(1,1))[0].plot3d()
sage: A.jmol_repr(A.testing_render_params())[0]
'draw line_1 diameter 2 arrow {0.0 0.0 0.0} {1.0 1.0 0.0} '
Note that we had to index the arrow to get the Arrow graphics primitive. We can also change the height
via the Graphics.plot3d() method, but only as a whole:
sage: A = arrow((0,0),(1,1)).plot3d(3)
sage: A.jmol_repr(A.testing_render_params())[0][0]
'draw line_1 diameter 2 arrow {0.0 0.0 3.0} {1.0 1.0 3.0} '
Optional arguments place both the head and tail outside the 𝑥𝑦-plane, but at different heights. This must
be done on the graphics primitive obtained by indexing:
sage: A=arrow((0,0),(1,1))[0].plot3d(3,4)
sage: A.jmol_repr(A.testing_render_params())[0]
'draw line_1 diameter 2 arrow {0.0 0.0 3.0} {1.0 1.0 4.0} '
get_minmax_data()
Returns a dictionary with the bounding box data.
EXAMPLES:
0.8
0.6
0.4
0.2
• linestyle - (default: 'solid') The style of the line, which is one of 'dashed', 'dotted',
'solid', 'dashdot', or '--', ':', '-', '-.', respectively.
• width - (default: 2) the width of the arrow shaft, in points
• color - (default: (0,0,1)) the color of the arrow (as an RGB tuple or a string)
• hue - the color of the arrow (as a number)
• arrowsize - the size of the arrowhead
• arrowshorten - the length in points to shorten the arrow (ignored if using path parameter)
• legend_label - the label for this item in the legend
• legend_color - the color for the legend label
• zorder - the layer level to draw the arrow– note that this is ignored in 3D plotting.
EXAMPLES:
A straight, blue arrow:
2.5
1.5
1
1 1.5 2 2.5 3
Make a red arrow:
2.5
1.5
0.5
-1
sage: arrow2d((-1,-1), (2,3), color='red')
Graphics object consisting of 1 graphics primitive
2.5
1.5
0.5
-1
2.5
1.5
1
1 1.5 2 2.5 3
2.5
1.5
1
1 1.5 2 2.5 3
0.5
-1 -0.5 0.5 1
-0.5
-1
If we want to draw the arrow between objects, for example, the boundaries of two lines, we can use the
arrowshorten option to make the arrow shorter by a certain number of points:
0.8
0.6
0.4
0.2
Extra options will get passed on to Graphics.show(), as long as they are valid:
2 up
1.5
0.5
-1 -0.5 0.5 1
1.8
1.6
1.4
1.2
1
-2 0 2 4 6
0.8
0.6
0.4
0.2
get_minmax_data()
Returns a dictionary with the bounding box data.
EXAMPLES:
sage: b = bezier_path([[(0,0),(.5,.5),(1,0)],[(.5,1),(0,0)]])
sage: d = b.get_minmax_data()
sage: d['xmin']
0.0
sage: d['xmax']
1.0
plot3d(z=0, **kwds)
Returns a 3D plot (Jmol) of the Bezier path. Since a BezierPath primitive contains only 𝑥, 𝑦 coor-
dinates, the path will be drawn in some plane (default is 𝑧 = 0). To create a Bezier path with nonzero
(and nonidentical) 𝑧 coordinates in the path and control points, use the function bezier3d() instead of
bezier_path().
EXAMPLES:
sage: b = bezier_path([[(0,0),(0,1),(1,0)]])
sage: A = b.plot3d()
sage: B = b.plot3d(z=2)
sage: A + B
Graphics3d Object
sage: bezier3d([[(0,0,0),(1,0,0),(0,1,0),(0,1,1)]])
Graphics3d Object
4 p5
3 c5
2p3 p4
1 c1 c4
c2
c3
p1 0.5 1 1.5 2 2.5 3 3.5 4
-1 p2
2.5
1.5
0.5
0.8
0.6
0.4
0.2
Extra options will get passed on to show(), as long as they are valid:
1
Graphics object consisting of 1 graphics primitive
sage: bezier_path([[(0,1),(.5,0),(1,1)]]).show(fontsize=50) # These are equivalent
0.8
0.6
0.4
0.2
0.20.40.60.8 1
4.4 Circles
get_minmax_data()
Returns a dictionary with the bounding box data.
EXAMPLES:
plot3d(z=0, **kwds)
Plots a 2D circle (actually a 50-gon) in 3D, with default height zero.
INPUT:
• z - optional 3D height above 𝑥𝑦-plane.
EXAMPLES:
This example uses this method implicitly, but does not pass the optional parameter z to this method:
Graphics3d Object
OPTIONS:
• alpha - default: 1
• fill - default: False
• thickness - default: 1
• linestyle - default: 'solid' (2D plotting only) The style of the line, which is one of 'dashed',
'dotted', 'solid', 'dashdot', or '--', ':', '-', '-.', respectively.
• edgecolor - default: ‘blue’ (2D plotting only)
• facecolor - default: ‘blue’ (2D plotting only, useful only if fill=True)
• rgbcolor - 2D or 3D plotting. This option overrides edgecolor and facecolor for 2D plotting.
• legend_label - the label for this item in the legend
• legend_color - the color for the legend label
EXAMPLES:
The default color is blue, the default linestyle is solid, but this is easy to change:
sage: c = circle((1,1), 1)
sage: c
Graphics object consisting of 1 graphics primitive
1.5
0.5
0.5 1 1.5 2
1.5
0.5
0.5 1 1.5 2
We can also use this command to plot three-dimensional circles parallel to the 𝑥𝑦-plane:
To correct the aspect ratio of certain graphics, it is necessary to show with a figsize of square dimensions:
sage: c.show(figsize=[5,5],xmin=-1,xmax=3,ymin=-1,ymax=3)
Here we make a more complicated plot, with many circles of different colors:
sage: g = Graphics()
sage: step=6; ocur=1/5; paths=16
sage: PI = math.pi # numerical for speed -- fine for graphics
sage: for r in range(1,paths+1):
....: for x,y in [((r+ocur)*math.cos(n), (r+ocur)*math.sin(n)) for n in
˓→srange(0, 2*PI+PI/step, PI/step)]:
300
200
100
-100
-200
-300
Note that the rgbcolor option overrides the other coloring options. This produces red fill in a blue circle:
The option hue overrides all other options, so be careful with its use. This produces a purplish filled circle:
3.5
2.5
2
1 1.5 2 2.5 3
3.5
2.5
2
1 1.5 2 2.5 3
3.5
2.5
2
1 1.5 2 2.5 3
6 the sun
1 2 3 4 5
sage: circle((4,5), 1, legend_label='the sun', legend_color='yellow').show(xmin=0,
˓→ ymin=0)
Extra options will get passed on to show(), as long as they are valid:
4.5 Disks
6 the sun
1 2 3 4 5
sage: D.options()['zorder']
3
sage: D.x
1.0
get_minmax_data()
Returns a dictionary with the bounding box data.
EXAMPLES:
plot3d(z=0, **kwds)
Plots a 2D disk (actually a 52-gon) in 3D, with default height zero.
INPUT:
• z - optional 3D height above 𝑥𝑦-plane.
AUTHORS:
• Karl-Dieter Crisman (05-09)
EXAMPLES:
Note that since thickness defaults to zero, it is best to change that option when using fill=False:
The previous two examples also illustrate using hue and rgbcolor as ways of specifying the color of the
graphic.
We can also use this command to plot three-dimensional disks parallel to the 𝑥𝑦-plane:
Extra options will get passed on to show(), as long as they are valid:
sage: disk((0, 0), 5, (0, pi/2), xmin=0, xmax=5, ymin=0, ymax=5, figsize=(2,2),
˓→rgbcolor=(1, 0, 1))
4.6 Ellipses
get_minmax_data()
Return a dictionary with the bounding box data.
The bounding box is computed to be as minimal as possible.
EXAMPLES:
An example without an angle:
plot3d()
Plotting in 3D is not implemented.
sage.plot.ellipse.ellipse(center, r1, r2, angle=0, edgecolor=’blue’, legend_color=None,
facecolor=’blue’, linestyle=’solid’, thickness=1, zorder=5, as-
pect_ratio=1.0, alpha=1, legend_label=None, fill=False, **options)
Return an ellipse centered at a point center = (x,y) with radii = r1,r2 and angle angle. Type ellipse.
options to see all options.
INPUT:
• center - 2-tuple of real numbers - coordinates of the center
• r1, r2 - positive real numbers - the radii of the ellipse
• angle - real number (default: 0) - the angle between the first axis and the horizontal
OPTIONS:
• alpha - default: 1 - transparency
• fill - default: False - whether to fill the ellipse or not
• thickness - default: 1 - thickness of the line
• linestyle - default: 'solid' - The style of the line, which is one of 'dashed', 'dotted',
'solid', 'dashdot', or '--', ':', '-', '-.', respectively.
• edgecolor - default: ‘black’ - color of the contour
• facecolor - default: ‘red’ - color of the filling
• rgbcolor - 2D or 3D plotting. This option overrides edgecolor and facecolor for 2D plotting.
• legend_label - the label for this item in the legend
• legend_color - the color for the legend label
EXAMPLES:
An ellipse centered at (0,0) with major and minor axes of lengths 2 and 1. Note that the default color is blue:
sage: ellipse((0,0),2,1)
Graphics object consisting of 1 graphics primitive
sage: ellipse((0,0),3,1,pi/6,fill=True,alpha=0.3,linestyle="dashed")
Graphics object consisting of 1 graphics primitive
sage: ellipse((0,0),3,1,pi/6,fill=True,alpha=0.3,linestyle="--")
Graphics object consisting of 1 graphics primitive
sage: ellipse((0,0),3,1,pi/6,fill=True,edgecolor='black',facecolor='red')
Graphics object consisting of 1 graphics primitive
We see that rgbcolor overrides these other options, as this plot is green:
sage: ellipse((0,0),3,1,pi/6,fill=True,edgecolor='black',facecolor='red',rgbcolor=
˓→'green')
sage: ellipse((0,0),2,1).aspect_ratio()
1.0
sage: ellipse((0,0,0),2,1)
Traceback (most recent call last):
...
NotImplementedError: plotting ellipse in 3D is not implemented
plot3d(z=0, **kwds)
Plots a 2D line in 3D, with default height zero.
EXAMPLES:
sage: E = EllipticCurve('37a').plot(thickness=5).plot3d()
sage: F = EllipticCurve('37a').plot(thickness=5).plot3d(z=2)
sage: E + F # long time (5s on sage.math, 2012)
Graphics3d Object
sage.plot.line.line(points, **kwds)
Returns either a 2-dimensional or 3-dimensional line depending on value of points.
INPUT:
• points - either a single point (as a tuple), a list of points, a single complex number, or a list of complex
numbers.
For information regarding additional arguments, see either line2d? or line3d?.
EXAMPLES:
Extra options will get passed on to show(), as long as they are valid:
We can also use a logarithmic scale if the data will support it:
sage: line([(1,2),(2,4),(3,4),(4,8),(4.5,32)],scale='loglog',base=2)
Graphics object consisting of 1 graphics primitive
sage: i = CC.0
sage: line([1+i, 2+3*i])
Graphics object consisting of 1 graphics primitive
sage: n = 4; h = 3; b = 2
sage: L = [[n*cos(pi*i/100)+h*cos((n/b)*pi*i/100),n*sin(pi*i/100)-h*sin((n/
˓→b)*pi*i/100)] for i in range(200)]
sage: n = 6; h = 5; b = 2
sage: L = [[n*cos(pi*i/100)+h*cos((n/b)*pi*i/100),n*sin(pi*i/100)-h*sin((n/
˓→b)*pi*i/100)] for i in range(200)]
sage: L = [[2*(1-4*cos(-pi/2+pi*i/100)^2),10*tan(-pi/2+pi*i/100)*(1-4*cos(-pi/
˓→2+pi*i/100)^2)] for i in range(1,100)]
A red plot of the Jacobi elliptic function sn(𝑥, 2), −3 < 𝑥 < 3:
A purple plot of the Riemann zeta function 𝜁(1/2 + 𝑖𝑡), 0 < 𝑡 < 30:
sage: i = CDF.gen()
sage: v = [zeta(0.5 + n/10 * i) for n in range(300)]
sage: L = [(z.real(), z.imag()) for z in v]
sage: line(L, rgbcolor=(3/4,1/2,5/8))
Graphics object consisting of 1 graphics primitive
A purple plot of the Hasse-Weil 𝐿-function 𝐿(𝐸, 1 + 𝑖𝑡), −1 < 𝑡 < 10:
sage: E = EllipticCurve('37a')
sage: vals = E.lseries().values_along_line(1-I, 1+10*I, 100) # critical line
sage: L = [(z[1].real(), z[1].imag()) for z in vals]
sage: line(L, rgbcolor=(3/4,1/2,5/8))
Graphics object consisting of 1 graphics primitive
4.8 Points
plot3d(z=0, **kwds)
Plots a two-dimensional point in 3-D, with default height zero.
INPUT:
• z - optional 3D height above 𝑥𝑦-plane. May be a list if self is a list of points.
EXAMPLES:
One point:
sage: A=point((1,1))
sage: a=A[0];a
Point set defined by 1 point(s)
sage: b=a.plot3d()
sage: A=point((1,1))
sage: a=A[0];a
Point set defined by 1 point(s)
sage: b=a.plot3d(z=3)
sage: b.loc[2]
3.0
Multiple points:
sage: A=point((1,1),size=22)
sage: a=A[0];a
Point set defined by 1 point(s)
sage: b=a.plot3d()
sage: b.size
22
sage: b=a.plot3d(pointsize=23) # only 2D valid option
sage: b.size
22
sage: b=a.plot3d(size=23) # correct keyword
sage: b.size
23
sage.plot.point.point(points, **kwds)
Returns either a 2-dimensional or 3-dimensional point or sum of points.
INPUT:
• points - either a single point (as a tuple), a list of points, a single complex number, or a list of complex
numbers.
For information regarding additional arguments, see either point2d? or point3d?.
See also:
sage.plot.point.point2d(), sage.plot.plot3d.shapes2.point3d()
EXAMPLES:
sage: point((1,2))
Graphics object consisting of 1 graphics primitive
sage: point((1,2,3))
Graphics3d Object
Extra options will get passed on to show(), as long as they are valid:
EXAMPLES:
A purple point from a single tuple or coordinates:
sage: point([])
Graphics object consisting of 0 graphics primitives
sage: import numpy; point(numpy.array([]))
Graphics object consisting of 0 graphics primitives
sage: A=point((1,1))
sage: a=A[0];a
Point set defined by 1 point(s)
sage: b=a.plot3d(z=3)
Here are some random larger red points, given as a list of tuples:
sage: point(((0.5, 0.5), (1, 2), (0.5, 0.9), (-1, -1)), rgbcolor=hue(1), size=30)
Graphics object consisting of 1 graphics primitive
Extra options will get passed on to show(), as long as they are valid:
For plotting data, we can use a logarithmic scale, as long as we are sure not to include any nonpositive points in
the logarithmic direction:
sage: point([(1,2),(2,4),(3,4),(4,8),(4.5,32)],scale='semilogy',base=2)
Graphics object consisting of 1 graphics primitive
Since Sage Version 4.4 (trac ticket #8599), the size of a 2d point can be given by the argument size instead of
pointsize. The argument pointsize is still supported:
sage.plot.point.points(points, **kwds)
Returns either a 2-dimensional or 3-dimensional point or sum of points.
INPUT:
• points - either a single point (as a tuple), a list of points, a single complex number, or a list of complex
numbers.
For information regarding additional arguments, see either point2d? or point3d?.
See also:
sage.plot.point.point2d(), sage.plot.plot3d.shapes2.point3d()
EXAMPLES:
sage: point((1,2))
Graphics object consisting of 1 graphics primitive
sage: point((1,2,3))
Graphics3d Object
Extra options will get passed on to show(), as long as they are valid:
4.9 Polygons
plot3d(z=0, **kwds)
Plots a 2D polygon in 3D, with default height zero.
INPUT:
• z - optional 3D height above 𝑥𝑦-plane, or a list of heights corresponding to the list of 2D polygon
points.
EXAMPLES:
A pentagon:
sage: polygon([(cos(t), sin(t)) for t in srange(0, 2*pi, 2*pi/5)]).plot3d()
Graphics3d Object
sage.plot.polygon.polygon(points, **options)
Returns either a 2-dimensional or 3-dimensional polygon depending on value of points.
For information regarding additional arguments, see either polygon2d() or polygon3d(). Options may
be found and set using the dictionaries polygon2d.options and polygon3d.options.
EXAMPLES:
sage: polygon([(0,0), (1,1), (0,1)])
Graphics object consisting of 1 graphics primitive
0.8
0.6
0.4
0.2
Extra options will get passed on to show(), as long as they are valid:
0
1 1.5 2 2.5 3 3.5 4 4.5 5
By default, polygons are filled in, but we can make them without a fill as well:
0
1 1.5 2 2.5 3 3.5 4 4.5 5
0
1 1.5 2 2.5 3 3.5 4 4.5 5
For filled polygons, one can use different colors for the border and the interior as follows:
A purple hexagon:
A green deltoid:
4 some form
-4 -3 -2 -1 1 2 3 4
-2
-4
0.5
-1 -0.5 0.5 1
-0.5
sage: L = [[-1+cos(pi*i/100)*(1+cos(pi*i/100)),2*sin(pi*i/100)*(1-cos(pi*i/100))]
˓→for i in range(200)]
-1 -0.5 0.5 1
-1
-2
A blue hypotrochoid:
sage: L = [[6*cos(pi*i/100)+5*cos((6/2)*pi*i/100),6*sin(pi*i/100)-5*sin((6/
˓→2)*pi*i/100)] for i in range(200)]
Another one:
sage: n = 4; h = 5; b = 2
sage: L = [[n*cos(pi*i/100)+h*cos((n/b)*pi*i/100),n*sin(pi*i/100)-h*sin((n/
˓→b)*pi*i/100)] for i in range(200)]
A purple epicycloid:
sage: m = 9; b = 1
sage: L = [[m*cos(pi*i/100)+b*cos((m/b)*pi*i/100),m*sin(pi*i/100)-b*sin((m/
˓→b)*pi*i/100)] for i in range(200)]
(continues on next page)
10
-10 -5 5 10
-5
-10
-4 -2 2 4 6 8
-2
-4
-6
-8
-10 -5 5 10
-5
A brown astroid:
0.5
-1 -0.5 0.5 1
-0.5
-1
1.5
0.5
-0.5
-1
-1.5
-0.5
-1
-1.5
-2
-2.5
-3
For you!
-1.5 -1 -0.5 0.5 1 1.5
-0.5
-1
-1.5
-2
-2.5
-3
Polygons have a default aspect ratio of 1.0:
sage: polygon2d([[1,2], [5,6], [5,0]]).aspect_ratio()
1.0
AUTHORS:
• David Joyner (2006-04-14): the long list of examples above.
AUTHORS:
• Hartmut Monien (2011 - 08)
class sage.plot.hyperbolic_arc.HyperbolicArc(A, B, options)
Bases: sage.plot.bezier_path.BezierPath
Primitive class for hyperbolic arc type. See hyperbolic_arc? for information about plotting a hyperbolic
arc in the complex plane.
INPUT:
sage: hyperbolic_arc(0, 1)
Graphics object consisting of 1 graphics primitive
AUTHORS:
• Hartmut Monien (2011-08)
• Vincent Delecroix (2014-11)
sage: hyperbolic_polygon([-1,3*I,2+2*I,1+I])
Graphics object consisting of 1 graphics primitive
sage.plot.hyperbolic_polygon.hyperbolic_triangle(a, b, c, **options)
Return a hyperbolic triangle in the hyperbolic plane with vertices (a,b,c).
Type ?hyperbolic_polygon to see all options.
INPUT:
• a, b, c – complex numbers in the upper half complex plane
2.5
1.5
0.5
2.5
1.5
0.5
OPTIONS:
• alpha – default: 1
• fill – default: False
• thickness – default: 1
• rgbcolor – default: 'blue'
• linestyle - (default: 'solid') The style of the line, which is one of 'dashed', 'dotted',
'solid', 'dashdot', or '--', ':', '-', '-.', respectively.
EXAMPLES:
√ √
Show a hyperbolic triangle with coordinates 0, 1/2 + 𝑖 3/2 and −1/2 + 𝑖 3/2:
0.8
0.6
0.4
0.2
1.6
1.4
1.2
0.8
0.6
0.4
0.2
0.5 1 1.5 2
4.12 Regular polygons in the upper half model for hyperbolic plane
AUTHORS:
• Javier Honrubia (2016-01)
class sage.plot.hyperbolic_regular_polygon.HyperbolicRegularPolygon(sides,
i_angle,
center,
options)
Bases: sage.plot.hyperbolic_polygon.HyperbolicPolygon
Primitive class for regular hyperbolic polygon type.
See hyperbolic_regular_polygon? for information about plotting a hyperbolic regular polygon in the
upper complex halfplane.
INPUT:
• sides – number of sides of the polygon
• i_angle – interior angle of the polygon
• center– center point as a complex number of the polygon
EXAMPLES:
Note that constructions should use hyperbolic_regular_polygon():
The code verifies is there exists a compact hyperbolic regular polygon with the given data, checking
where 𝑠 is sides and 𝛼 is i_angle`. This raises an error if the ``i_angle is less than
the minimum to generate a compact polygon:
It is an error to give a center outside the upper half plane in this model
sage.plot.hyperbolic_regular_polygon.hyperbolic_regular_polygon(sides,
i_angle, cen-
ter=1.00000000000000*I,
rgb-
color=’blue’,
thickness=1,
zorder=2,
alpha=1,
linestyle=’solid’,
fill=False,
**options)
Return a hyperbolic regular polygon in the upper half model of Hyperbolic plane given the number of sides,
interior angle and possibly a center.
Type ?hyperbolic_regular_polygon to see all options.
INPUT:
• sides – number of sides of the polygon
• i_angle – interior angle of the polygon
• center – (default: 𝑖) hyperbolic center point (complex number) of the polygon
OPTIONS:
• alpha – default: 1
• fill – default: False
• thickness – default: 1
• rgbcolor – default: 'blue'
• linestyle – (default: 'solid') the style of the line, which can be one of the following:
– 'dashed' or '--'
– 'dotted' or ':'
– 'solid' or '-'
– 'dashdot' or '-.'
EXAMPLES:
Show a hyperbolic regular polygon with 6 sides and square angles:
sage: g.plot()
Graphics object consisting of 1 graphics primitive
The code verifies is there exists a hyperbolic regular polygon with the given data, checking
4.12. Regular polygons in the upper half model for hyperbolic plane 383
Sage Reference Manual: 2D Graphics, Release 8.8
2.5
1.5
0.5
-1 -0.5 0 0.5 1
1 2 3 4 5
4.12. Regular polygons in the upper half model for hyperbolic plane 385
Sage Reference Manual: 2D Graphics, Release 8.8
where 𝑠 is sides and 𝛼 is i_angle`. This raises an error if the ``i_angle is less than
the minimum to generate a compact polygon:
It is an error to give a center outside the upper half plane in this model:
FIVE
This file contains the definition of the classes Graphics and GraphicsArray. Usually, you don’t create these
classes directly (although you can do it), you would use plot() or graphics_array() instead.
AUTHORS:
• Jeroen Demeyer (2012-04-19): split off this file from plot.py (trac ticket #12857)
• Punarbasu Purkayastha (2012-05-20): Add logarithmic scale (trac ticket #4529)
• Emily Chen (2013-01-05): Add documentation for show() figsize parameter (trac ticket #5956)
• Eric Gourgoulhon (2015-03-19): Add parameter axes_labels_size (trac ticket #18004)
class sage.plot.graphics.Graphics
Bases: sage.misc.fast_methods.WithEqualityById, sage.structure.sage_object.
SageObject
The Graphics object is an empty list of graphics objects. It is useful to use this object when initializing a for
loop where different graphics object will be added to the empty object.
EXAMPLES:
Here we make a graphic of embedded isosceles triangles, coloring each one with a different color as we go:
We can change the scale of the axes in the graphics before displaying.:
387
Sage Reference Manual: 2D Graphics, Release 8.8
_rich_repr_(display_manager, **kwds)
Rich Output Magic Method
See sage.repl.rich_output for details.
EXAMPLES:
add_primitive(primitive)
Adds a primitive to this graphics object.
EXAMPLES:
We give a very explicit example:
sage: G = Graphics()
sage: from sage.plot.line import Line
sage: from sage.plot.arrow import Arrow
sage: L = Line([3,4,2,7,-2],[1,2,e,4,5.],{'alpha':1,'thickness':2,'rgbcolor
˓→':(0,1,1),'legend_label':''})
sage: A = Arrow(2,-5,.1,.2,{'width':3,'head':0,'rgbcolor':(1,0,0),'linestyle':
˓→'dashed','zorder':8,'legend_label':''})
sage: G.add_primitive(L)
sage: G.add_primitive(A)
sage: G
Graphics object consisting of 2 graphics primitives
aspect_ratio()
Get the current aspect ratio, which is the ratio of height to width of a unit square, or ‘automatic’.
OUTPUT: a positive float (height/width of a unit square), or ‘automatic’ (expand to fill the figure).
EXAMPLES:
The default aspect ratio for a new blank Graphics object is ‘automatic’:
sage: P = Graphics()
sage: P.aspect_ratio()
'automatic'
The aspect ratio can be explicitly set different than the object’s default:
sage: P = circle((1,1), 1)
sage: P.aspect_ratio()
1.0
sage: P.set_aspect_ratio(2)
sage: P.aspect_ratio()
2.0
(continues on next page)
axes(show=None)
Set whether or not the 𝑥 and 𝑦 axes are shown by default.
INPUT:
• show - bool
If called with no input, return the current axes setting.
EXAMPLES:
sage: L.axes()
True
But we turn them off, and verify that they are off
sage: L.axes(False)
sage: L.axes()
False
sage: L
Graphics object consisting of 1 graphics primitive
axes_color(c=None)
Set the axes color.
If called with no input, return the current axes_color setting.
INPUT:
• c - an RGB color 3-tuple, where each tuple entry is a float between 0 and 1
EXAMPLES: We create a line, which has like everything a default axes color of black.
sage: L.axes_color((1,0,0))
sage: L.axes_color()
(1.0, 0.0, 0.0)
When we display the plot, we’ll see a blue triangle and bright red axes.
sage: L
Graphics object consisting of 1 graphics primitive
axes_label_color(c=None)
Set the color of the axes labels.
The axes labels are placed at the edge of the x and y axes, and are not on by default (use the axes_labels
command to set them; see the example below). This function just changes their color.
INPUT:
• c - an RGB 3-tuple of numbers between 0 and 1
If called with no input, return the current axes_label_color setting.
EXAMPLES: We create a plot, which by default has axes label color black.
sage: p.axes_label_color((1,0,0))
sage: p.axes_label_color()
(1.0, 0.0, 0.0)
sage: p
Graphics object consisting of 1 graphics primitive
axes_labels(l=None)
Set the axes labels.
INPUT:
• l - (default: None) a list of two strings or None
OUTPUT: a 2-tuple of strings
If l is None, returns the current axes_labels, which is itself by default None. The default labels are
both empty.
EXAMPLES: We create a plot and put x and y axes labels on it.
sage: p
Graphics object consisting of 1 graphics primitive
Notice that some may prefer axes labels which are not typeset:
sage: c = circle((0,0), 1)
sage: c.axes_labels(['axe des abscisses', u'axe des ordonnées'])
sage: c._axes_labels
('axe des abscisses', u'axe des ordonnées')
axes_labels_size(s=None)
Set the relative size of axes labels w.r.t. the axes tick marks.
INPUT:
• s - float, relative size of axes labels w.r.t. to the tick marks, the size of the tick marks being set by
fontsize().
If called with no input, return the current relative size.
EXAMPLES:
Now the axes labels are large w.r.t. the tick marks:
sage: p
Graphics object consisting of 1 graphics primitive
axes_width(w=None)
Set the axes width. Use this to draw a plot with really fat or really thin axes.
INPUT:
• w - a float
If called with no input, return the current axes_width setting.
EXAMPLES: We create a plot, see the default axes width (with funny Python float rounding), then reset
the width to 10 (very fat).
Finally we plot the result, which is a graph with very fat axes.
sage: p
Graphics object consisting of 1 graphics primitive
description()
Print a textual description to stdout.
This method is mostly used for doctests.
EXAMPLES:
sage: print(polytopes.hypercube(2).plot().description())
Polygon defined by 4 points: [(1.0, 1.0), (-1.0, 1.0), (-1.0, -1.0), (1.0, -1.
˓→0)]
fontsize(s=None)
Set the font size of axes labels and tick marks.
Note that the relative size of the axes labels font w.r.t. the tick marks font can be adjusted via
axes_labels_size().
INPUT:
• s - integer, a font size in points.
If called with no input, return the current fontsize.
EXAMPLES:
All the numbers on the axes will be very large in this plot:
sage: L
Graphics object consisting of 1 graphics primitive
get_axes_range()
Returns a dictionary of the range of the axes for this graphics object. This is fall back to the ranges in
get_minmax_data() for any value which the user has not explicitly set.
Warning: Changing the dictionary returned by this function does not change the axes range for this
object. To do that, use the set_axes_range() method.
EXAMPLES:
get_minmax_data()
Return the x and y coordinate minimum and maximum
Warning: The returned dictionary is mutable, but changing it does not change the
xmin/xmax/ymin/ymax data. The minmax data is a function of the primitives which make up this
Graphics object. To change the range of the axes, call methods xmin(), xmax(), ymin(), ymax(),
or set_axes_range().
OUTPUT:
A dictionary whose keys give the xmin, xmax, ymin, and ymax data for this graphic.
EXAMPLES:
sage: g.ymax(10)
sage: list(sorted(g.get_minmax_data().items()))
[('xmax', 3.0), ('xmin', -1.0), ('ymax', 2.0), ('ymin', 1.0)]
The width/height ratio (in output units, after factoring in the chosen aspect ratio) of the plot is limited to
10−15 . . . 1015 , otherwise floating point errors cause problems in matplotlib:
legend(show=None)
Set whether or not the legend is shown by default.
INPUT:
• show - (default: None) a boolean
If called with no input, return the current legend setting.
EXAMPLES:
By default no legend is displayed:
sage: P = plot(sin)
sage: P.legend()
False
sage: P.legend(False)
sage: P.legend()
False
sage: P.legend(True)
sage: P # show with the legend
Graphics object consisting of 1 graphics primitive
sage: c = circle((1,1),1)
sage: print(c.matplotlib())
Figure(640x480)
To obtain the first matplotlib axes object inside of the figure, you can do something like the following.
For input parameters, see the documentation for the show() method (this function accepts all except the
transparent argument).
plot()
Draw a 2D plot of this graphics object, which just returns this object since this is already a 2D graphics
object.
EXAMPLES:
sage: S = circle((0,0), 2)
sage: S.plot() is S
True
sage: S.plot(hey="hou")
Traceback (most recent call last):
...
TypeError: plot() got an unexpected keyword argument 'hey'
plot3d(z=0, **kwds)
Returns an embedding of this 2D plot into the xy-plane of 3D space, as a 3D plot object. An optional
parameter z can be given to specify the z-coordinate.
EXAMPLES:
By default, the figure grows to include all of the graphics and text, so the final image may not be ex-
actly the figure size you specified. If you want a figure to be exactly a certain size, specify the keyword
fig_tight=False:
You can also pass extra options to the plot command instead of this method, e.g.
will save the same plot as the one shown by this command:
Note: Not all image types are necessarily implemented for all graphics types. See save() for more
details.
EXAMPLES:
set_aspect_ratio(ratio)
Set the aspect ratio, which is the ratio of height and width of a unit square (i.e., height/width of a unit
square), or ‘automatic’ (expand to fill the figure).
INPUT:
• ratio - a positive real number or ‘automatic’
EXAMPLES: We create a plot of the upper half of a circle, but it doesn’t look round because the aspect
ratio is off:
sage: P = plot(sqrt(1-x^2),(x,-1,1)); P
Graphics object consisting of 1 graphics primitive
sage: P.set_aspect_ratio(1)
sage: P.aspect_ratio()
1.0
(continues on next page)
Note that the aspect ratio is inherited upon addition (which takes the max of aspect ratios of objects whose
aspect ratio has been set):
sage: P + plot(sqrt(4-x^2),(x,-2,2))
Graphics object consisting of 2 graphics primitives
In the following example, both plots produce a circle that looks twice as tall as wide:
set_legend_options(**kwds)
Set various legend options.
INPUT:
• title - (default: None) string, the legend title
• ncol - (default: 1) positive integer, the number of columns
• columnspacing - (default: None) the spacing between columns
• borderaxespad - (default: None) float, length between the axes and the legend
• back_color - (default: ‘white’) This parameter can be a string denoting a color or an RGB tuple.
The string can be a color name as in (‘red’, ‘green’, ‘yellow’, . . . ) or a floating point number like
‘0.8’ which gets expanded to (0.8, 0.8, 0.8). The tuple form is just a floating point RGB tuple with all
values ranging from 0 to 1.
• handlelength - (default: 0.05) float, the length of the legend handles
• handletextpad - (default: 0.5) float, the pad between the legend handle and text
• labelspacing - (default: 0.02) float, vertical space between legend entries
• loc - (default: ‘best’) May be a string, an integer or a tuple. String or integer inputs must be
one of the following:
– 0, ‘best’
– 1, ‘upper right’
– 2, ‘upper left’
– 3, ‘lower left’
– 4, ‘lower right’
– 5, ‘right’
– 6, ‘center left’
– 7, ‘center right’
– 8, ‘lower center’
– 9, ‘upper center’
– 10, ‘center’
– Tuple arguments represent an absolute (x, y) position on the plot in axes coordinates (meaning
from 0 to 1 in each direction).
• markerscale - (default: 0.6) float, how much to scale the markers in the legend.
• numpoints - (default: 2) integer, the number of points in the legend for line
• borderpad - (default: 0.6) float, the fractional whitespace inside the legend border (between 0 and
1)
• font_family - (default: ‘sans-serif’) string, one of ‘serif’, ‘sans-serif’, ‘cursive’, ‘fantasy’,
‘monospace’
• font_style - (default: ‘normal’) string, one of ‘normal’, ‘italic’, ‘oblique’
• font_variant - (default: ‘normal’) string, one of ‘normal’, ‘small-caps’
• font_weight - (default: ‘medium’) string, one of ‘black’, ‘extra bold’, ‘bold’, ‘semibold’,
‘medium’, ‘normal’, ‘light’
• font_size - (default: ‘medium’) string, one of ‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’,
‘x-large’, ‘xx-large’ or an absolute font size (e.g. 12)
• shadow - (default: True) boolean - draw a shadow behind the legend
• fancybox - (default: False) a boolean. If True, draws a frame with a round fancybox.
These are all keyword arguments.
OUTPUT: a dictionary of all current legend options
EXAMPLES:
By default, no options are set:
sage: p.set_legend_options(shadow=False)
sage: p.set_legend_options()['shadow']
False
To set the legend position to the center of the plot, all these methods are roughly equivalent:
sage: p.set_legend_options(loc='center'); p
Graphics object consisting of 1 graphics primitive
sage: p.set_legend_options(loc=10); p
Graphics object consisting of 1 graphics primitive
– [xlist,ylist]: a tuple or list containing two elements, where xlist (or ylist) can be any of the follow-
ing.
Warning: This should only be used with the ticks option using nice rational multiples of that
constant!
– If one of the entries is the string "latex", then the formatting will be nice typesetting of the
ticks. This is intended to be used when the tick locator for at least one of the axes is a list including
some symbolic elements. This uses matplotlib’s internal LaTeX rendering engine. If you want to
use an external LaTeX compiler, then set the keyword option typeset. See examples.
– If the first entry is a list of strings (or numbers), then the formatting for the horizontal axis will be
typeset with the strings present in the list. Each entry of the list of strings must be provided with
a corresponding number in the first entry of ticks to indicate its position on the axis. To typeset
the strings with "latex" enclose them within "$" symbols. To have similar custom formatting
of the labels along the vertical axis, the second entry must be a list of strings and the second entry
of ticks must also be a list of numbers which give the positions of the labels. See the examples
below.
Note:
– If the scale is "linear", then irrespective of what base is set to, it will default to 10 and
will remain unused.
You can make the picture larger by changing figsize with width, height each having a maximum value
of 327 inches at default dpi:
sage: p = ellipse((0,0),4,1)
sage: p.show(figsize=[327,10],dpi=100)
sage: p.show(figsize=[328,10],dpi=80)
You can also label the axes. Putting something in dollar signs formats it as a mathematical expression:
You can also provide the position for the title to the plot. In the plot below the title is placed on the bottom
left of the figure.:
If you want all the text to be rendered by using an external LaTeX installation then set the typeset to
"latex". This requires that LaTeX, dvipng and Ghostscript be installed:
If you want all the text in your plot to use Type 1 fonts, then set the typeset option to "type1". This
requires that LaTeX, dvipng and Ghostscript be installed:
Prior to trac ticket #19485, legends by default had a shadowless gray background. This behavior can be
recovered by passing in certain legend_options:
We can change the scale of the axes in the graphics before displaying:
We can change the base of the logarithm too. The following changes the vertical axis to be on log scale,
and with base 2. Note that the base argument will ignore any changes to the axis which is in linear scale.:
The base need not be an integer, though it does have to be made a float.:
Logarithmic scale can be used for various kinds of plots. Here are some examples.:
sage: c = circle((0,0), 1)
sage: c.show(gridlines=True)
sage: c.show(gridlines="automatic")
sage: c.show(gridlines="major")
Add grid lines at the major and minor ticks of the axes.
sage: u,v = var('u v')
sage: f = exp(-(u^2+v^2))
sage: p = plot_vector_field(f.gradient(), (u,-2,2), (v,-2,2))
sage: p.show(gridlines="minor")
sage: M = MatrixSpace(QQ,10).random_element()
sage: matrix_plot(M).show(gridlines=True)
By default, Sage increases the horizontal and vertical axes limits by a certain percentage in all directions.
This is controlled by the axes_pad parameter. Increasing the range of the axes helps avoid problems
with lines and dots being clipped because the linewidth extends beyond the axes. To get axes limits that
are exactly what is specified, set axes_pad to zero. Compare the following two examples
The behavior of the axes_pad parameter is different if the axis is in the "log" scale. If 𝑏 is the base
of the axis, the minimum value of the axis, is decreased by the factor 1/𝑏axes_pad of the minimum and the
maximum value of the axis is increased by the same factor of the maximum value. Compare the axes in
the following two plots to see the difference.
Via matplotlib, Sage allows setting of custom ticks. See above for more details.
Here the labels are not so useful:
Or no ticks at all:
But be careful to leave enough room for at least two major ticks, so that the user can tell what the scale is:
sage: plot(x^2,(x,1,8),ticks=6).show()
Traceback (most recent call last):
...
ValueError: Expand the range of the independent variable to
allow two multiples of your tick locator (option `ticks`).
We can also do custom formatting if you need it. See above for full details:
sage: plot(2*x+1,(x,0,5),ticks=[[0,1,e,pi,sqrt(20)],2],tick_formatter="latex")
Graphics object consisting of 1 graphics primitive
sage: plot(sin(x),(x,0,2*pi),ticks=pi/3,tick_formatter=pi)
Graphics object consisting of 1 graphics primitive
But keep in mind that you will get exactly the formatting you asked for if you specify both formatters. The
first syntax is recommended for best style in that case.
sage: plot(arcsin(x),(x,-1,1),ticks=[None,pi/6],tick_formatter=["latex",pi])
˓→# Nice-looking!
sage: plot(arcsin(x),(x,-1,1),ticks=[None,pi/6],tick_formatter=[None,pi]) #
˓→Not so nice-looking
Custom tick labels can be provided by providing the keyword tick_formatter with the list of labels,
and simultaneously providing the keyword ticks with the positions of the labels.
The following sets the custom tick labels only along the horizontal axis.
If the number of tick labels do not match the number of positions of tick labels, then it results in an error.:
When using logarithmic scale along the axis, make sure to have enough room for two ticks so that the user
can tell what the scale is. This can be effected by increasing the range of the independent variable, or by
changing the base, or by providing enough tick locations by using the ticks parameter.
By default, Sage will expand the variable range so that at least two ticks are included along the logarithmic
axis. However, if you specify ticks manually, this safety measure can be defeated:
This one works, since the horizontal axis is automatically expanded to contain two ticks and the vertical
axis is provided with two ticks:
Another example in the log scale where both the axes are automatically expanded to show two major ticks:
When using title_pos, it must be ensured that a list or a tuple of length two is used. Otherwise, a
warning is raised:
tick_label_color(c=None)
Set the color of the axes tick labels.
INPUT:
• c - an RGB 3-tuple of numbers between 0 and 1
xmax(xmax=None)
EXAMPLES:
xmin(xmin=None)
EXAMPLES:
ymax(ymax=None)
EXAMPLES:
ymin(ymin=None)
EXAMPLES:
class sage.plot.graphics.GraphicsArray(array)
Bases: sage.misc.fast_methods.WithEqualityById, sage.structure.sage_object.
SageObject
GraphicsArray takes a (𝑚 x 𝑛) list of lists of graphics objects and plots them all on one canvas.
_rich_repr_(display_manager, **kwds)
Rich Output Magic Method
See sage.repl.rich_output for details.
EXAMPLES:
append(g)
Appends a graphic to the array. Currently not implemented.
ncols()
Number of columns of the graphics array.
EXAMPLES:
sage: R = rainbow(6)
sage: L = [plot(x^n,(x,0,1),color=R[n]) for n in range(6)]
sage: G = graphics_array(L,2,3)
sage: G.ncols()
3
sage: graphics_array(L).ncols()
6
nrows()
Number of rows of the graphics array.
EXAMPLES:
sage: R = rainbow(6)
sage: L = [plot(x^n,(x,0,1),color=R[n]) for n in range(6)]
sage: G = graphics_array(L,2,3)
sage: G.nrows()
2
sage: graphics_array(L).nrows()
1
plot()
Draw a 2D plot of this graphics object, which just returns this object since this is already a 2D graphics
object.
EXAMPLES:
sage: g1 = plot(cos(20*x)*exp(-2*x), 0, 1)
sage: g2 = plot(2*exp(-30*x) - exp(-3*x), 0, 1)
sage: S = graphics_array([g1, g2], 2, 1)
sage: S.plot() is S
True
– .eps,
– .pdf,
– .png,
– .ps,
– .sobj (for a Sage object you can load later),
– .svg,
– empty extension will be treated as .sobj.
• dpi - dots per inch
• figsize - width or [width, height] See documentation for sage.plot.graphics.
Graphics.show() for more details.
• axes - (default: True)
EXAMPLES:
sage: F = tmp_filename(ext='.png')
sage: L = [plot(sin(k*x),(x,-pi,pi)) for k in [1..3]]
sage: G = graphics_array(L)
sage: G.save(F, dpi=500, axes=False) # long time (6s on sage.math, 2012)
Note: Not all image types are necessarily implemented for all graphics types. See save() for more
details.
EXAMPLES:
sage: G = graphics_array(plots)
sage: G.save_image(tmp_filename(ext='.png'))
show(**kwds)
Show this graphics array immediately.
This method attempts to display the graphics immediately, without waiting for the currently running code
(if any) to return to the command line. Be careful, calling it from within a loop will potentially launch a
large number of external viewer programs.
OPTIONAL INPUT:
• dpi - dots per inch
• figsize - width or [width, height] See the documentation for sage.plot.graphics.
Graphics.show() for more information.
• axes - (default: True)
• fontsize - positive integer
• frame - (default: False) draw a frame around the image
OUTPUT:
This method does not return anything. Use save() if you want to save the figure as an image.
EXAMPLES:
This draws a graphics array with four trig plots and no axes in any of the plots:
sage.plot.graphics.is_Graphics(x)
Return True if 𝑥 is a Graphics object.
EXAMPLES:
class sage.plot.primitive.GraphicPrimitive(options)
Bases: sage.misc.fast_methods.WithEqualityById, sage.structure.sage_object.
SageObject
Base class for graphics primitives, e.g., things that knows how to draw themselves in 2D.
EXAMPLES:
We create an object that derives from GraphicPrimitive:
options()
Return the dictionary of options for this graphics primitive.
By default this function verifies that the options are all valid; if any aren’t, then a verbose message is
printed with level 0.
EXAMPLES:
plot3d(**kwds)
Plots 3D version of 2D graphics object. Not implemented for base class.
EXAMPLES:
set_options(new_options)
Change the options to 𝑛𝑒𝑤𝑜 𝑝𝑡𝑖𝑜𝑛𝑠.
EXAMPLES:
set_zorder(zorder)
Set the layer in which to draw the object.
EXAMPLES:
class sage.plot.primitive.GraphicPrimitive_xydata(options)
Bases: sage.plot.primitive.GraphicPrimitive
get_minmax_data()
Returns a dictionary with the bounding box data.
EXAMPLES:
sage: d['ymin']
0.0
sage: d['xmin']
1.0
sage.plot.misc.get_matplotlib_linestyle(linestyle, return_type)
Function which translates between matplotlib linestyle in short notation (i.e. ‘-‘, ‘–’, ‘:’, ‘-.’) and long notation
(i.e. ‘solid’, ‘dashed’, ‘dotted’, ‘dashdot’ ).
If linestyle is none of these allowed options, the function raises a ValueError.
INPUT:
• linestyle - The style of the line, which is one of
– "-" or "solid"
– "--" or "dashed"
– "-." or "dash dot"
– ":" or "dotted"
– "None" or " " or "" (nothing)
The linestyle can also be prefixed with a drawing style (e.g., "steps--")
– "default" (connect the points with straight lines)
– "steps" or "steps-pre" (step function; horizontal line is to the left of point)
– "steps-mid" (step function; points are in the middle of horizontal lines)
– "steps-post" (step function; horizontal line is to the right of point)
If linestyle is None (of type NoneType), then we return it back unmodified.
• return_type - The type of linestyle that should be output. This argument takes only two values -
"long" or "short".
EXAMPLES:
Here is an example how to call this function:
• ranges – a list of ranges. A range can be a 2-tuple of numbers specifying the minimum and maximum,
or a 3-tuple giving the variable explicitly.
• plot_points – a tuple of integers specifying the number of plot points for each range. If a single
number is specified, it will be the value for all ranges. This defaults to 2.
• return_vars – (default False) If True, return the variables, in order.
OUTPUT:
• fast_funcs - if only one function passed, then a fast callable function. If funcs is a list or tuple, then a
tuple of fast callable functions is returned.
• range_specs - a list of range_specs: for each range, a tuple is returned of the form (range_min,
range_max, range_step) such that srange(range_min, range_max, range_step,
include_endpoint=True) gives the correct points for evaluation.
EXAMPLES:
sage: x,y,z=var('x,y,z')
sage: f(x,y)=x+y-z
sage: g(x,y)=x+y
sage: h(y)=-y
sage: sage.plot.misc.setup_for_eval_on_grid(f, [(0, 2),(1,3),(-4,1)], plot_
˓→points=5)
(<sage.ext...>, [(0.0, 2.0, 0.5), (1.0, 3.0, 0.5), (-4.0, 1.0, 1.25)])
sage: sage.plot.misc.setup_for_eval_on_grid([g,h], [(0, 2),(-1,1)], plot_points=5)
((<sage.ext...>, <sage.ext...>), [(0.0, 2.0, 0.5), (-1.0, 1.0, 0.5)])
sage: sage.plot.misc.setup_for_eval_on_grid([sin,cos], [(-1,1)], plot_points=9)
((<sage.ext...>, <sage.ext...>), [(-1.0, 1.0, 0.25)])
sage: sage.plot.misc.setup_for_eval_on_grid([lambda x: x^2,cos], [(-1,1)], plot_
˓→points=9)
˓→xmax)
sage.plot.misc.unify_arguments(funcs)
Return a tuple of variables of the functions, as well as the number of “free” variables (i.e., variables that defined
in a callable function).
INPUT:
• funcs – a list of functions; these can be symbolic expressions, polynomials, etc
OUTPUT: functions, expected arguments
• A tuple of variables in the functions
• A tuple of variables that were “free” in the functions
EXAMPLES:
sage: x,y,z=var('x,y,z')
sage: f(x,y)=x+y-z
sage: g(x,y)=x+y
sage: h(y)=-y
sage: sage.plot.misc.unify_arguments((f,g,h))
((x, y, z), (z,))
sage: sage.plot.misc.unify_arguments((g,h))
((x, y), ())
sage: sage.plot.misc.unify_arguments((f,z))
((x, y, z), (z,))
sage: sage.plot.misc.unify_arguments((h,z))
((y, z), (z,))
sage: sage.plot.misc.unify_arguments((x+y,x-y))
((x, y), (x, y))
SIX
• Index
• Module Index
• Search Page
417
Sage Reference Manual: 2D Graphics, Release 8.8
g
sage.graphs.graph_plot, 277
p
sage.plot.animate, 157
sage.plot.arc, 313
sage.plot.arrow, 315
sage.plot.bar_chart, 275
sage.plot.bezier_path, 328
sage.plot.circle, 334
sage.plot.colors, 147
sage.plot.complex_plot, 169
sage.plot.contour_plot, 177
sage.plot.density_plot, 244
sage.plot.disk, 344
sage.plot.ellipse, 348
sage.plot.graphics, 387
sage.plot.histogram, 272
sage.plot.hyperbolic_arc, 375
sage.plot.hyperbolic_polygon, 376
sage.plot.hyperbolic_regular_polygon, 382
sage.plot.line, 350
sage.plot.matrix_plot, 307
sage.plot.misc, 413
sage.plot.plot, 1
sage.plot.plot_field, 252
sage.plot.point, 354
sage.plot.polygon, 359
sage.plot.primitive, 411
sage.plot.scatter_plot, 270
sage.plot.step, 271
sage.plot.streamline_plot, 263
sage.plot.text, 135
419
Sage Reference Manual: 2D Graphics, Release 8.8
Symbols
_rich_repr_() (sage.plot.graphics.Graphics method), 388
_rich_repr_() (sage.plot.graphics.GraphicsArray method), 408
A
adaptive_refinement() (in module sage.plot.plot), 26
add_frame() (sage.plot.animate.APngAssembler method), 160
add_primitive() (sage.plot.graphics.Graphics method), 388
animate() (in module sage.plot.animate), 166
Animation (class in sage.plot.animate), 160
apng() (sage.plot.animate.Animation method), 161
APngAssembler (class in sage.plot.animate), 159
append() (sage.plot.graphics.GraphicsArray method), 409
Arc (class in sage.plot.arc), 313
arc() (in module sage.plot.arc), 314
Arrow (class in sage.plot.arrow), 315
arrow() (in module sage.plot.arrow), 316
arrow2d() (in module sage.plot.arrow), 317
aspect_ratio() (sage.plot.graphics.Graphics method), 388
axes() (sage.plot.graphics.Graphics method), 389
axes_color() (sage.plot.graphics.Graphics method), 389
axes_label_color() (sage.plot.graphics.Graphics method), 389
axes_labels() (sage.plot.graphics.Graphics method), 390
axes_labels_size() (sage.plot.graphics.Graphics method), 391
axes_range() (sage.plot.graphics.Graphics method), 391
axes_width() (sage.plot.graphics.Graphics method), 391
B
bar_chart() (in module sage.plot.bar_chart), 275
BarChart (class in sage.plot.bar_chart), 275
bezier_path() (in module sage.plot.bezier_path), 330
bezier_path() (sage.plot.arc.Arc method), 313
BezierPath (class in sage.plot.bezier_path), 328
blend() (sage.plot.colors.Color method), 148
C
check_color_data() (in module sage.plot.colors), 151
421
Sage Reference Manual: 2D Graphics, Release 8.8
D
darker() (sage.plot.colors.Color method), 148
density_plot() (in module sage.plot.density_plot), 244
DensityPlot (class in sage.plot.density_plot), 244
description() (sage.plot.graphics.Graphics method), 392
Disk (class in sage.plot.disk), 344
disk() (in module sage.plot.disk), 347
E
Ellipse (class in sage.plot.ellipse), 348
ellipse() (in module sage.plot.ellipse), 349
equify() (in module sage.plot.contour_plot), 212
F
ffmpeg() (sage.plot.animate.Animation method), 161
float_to_html() (in module sage.plot.colors), 151
float_to_integer() (in module sage.plot.colors), 152
fontsize() (sage.plot.graphics.Graphics method), 392
G
generate_plot_points() (in module sage.plot.plot), 26
get_axes_range() (sage.plot.graphics.Graphics method), 392
get_cmap() (in module sage.plot.colors), 152
get_matplotlib_linestyle() (in module sage.plot.misc), 413
get_minmax_data() (sage.plot.arc.Arc method), 313
get_minmax_data() (sage.plot.arrow.Arrow method), 315
get_minmax_data() (sage.plot.arrow.CurveArrow method), 316
get_minmax_data() (sage.plot.bar_chart.BarChart method), 275
get_minmax_data() (sage.plot.bezier_path.BezierPath method), 328
get_minmax_data() (sage.plot.circle.Circle method), 335
get_minmax_data() (sage.plot.complex_plot.ComplexPlot method), 169
get_minmax_data() (sage.plot.contour_plot.ContourPlot method), 177
get_minmax_data() (sage.plot.density_plot.DensityPlot method), 244
get_minmax_data() (sage.plot.disk.Disk method), 346
get_minmax_data() (sage.plot.ellipse.Ellipse method), 348
get_minmax_data() (sage.plot.graphics.Graphics method), 393
get_minmax_data() (sage.plot.histogram.Histogram method), 272
get_minmax_data() (sage.plot.matrix_plot.MatrixPlot method), 308
422 Index
Sage Reference Manual: 2D Graphics, Release 8.8
H
Histogram (class in sage.plot.histogram), 272
histogram() (in module sage.plot.histogram), 273
hls() (sage.plot.colors.Color method), 148
hsl() (sage.plot.colors.Color method), 149
hsv() (sage.plot.colors.Color method), 149
html_color() (sage.plot.colors.Color method), 149
html_to_float() (in module sage.plot.colors), 153
hue() (in module sage.plot.colors), 153
hyperbolic_arc() (in module sage.plot.hyperbolic_arc), 376
hyperbolic_polygon() (in module sage.plot.hyperbolic_polygon), 377
hyperbolic_regular_polygon() (in module sage.plot.hyperbolic_regular_polygon), 382
hyperbolic_triangle() (in module sage.plot.hyperbolic_polygon), 377
HyperbolicArc (class in sage.plot.hyperbolic_arc), 375
HyperbolicPolygon (class in sage.plot.hyperbolic_polygon), 376
HyperbolicRegularPolygon (class in sage.plot.hyperbolic_regular_polygon), 382
I
implicit_plot() (in module sage.plot.contour_plot), 214
is_Graphics() (in module sage.plot.graphics), 411
L
layout_tree() (sage.graphs.graph_plot.GraphPlot method), 282
legend() (sage.plot.graphics.Graphics method), 393
lighter() (sage.plot.colors.Color method), 150
Line (class in sage.plot.line), 350
line() (in module sage.plot.line), 350
line2d() (in module sage.plot.line), 351
list_plot() (in module sage.plot.plot), 29
list_plot_loglog() (in module sage.plot.plot), 41
list_plot_semilogx() (in module sage.plot.plot), 44
list_plot_semilogy() (in module sage.plot.plot), 45
load_maps() (sage.plot.colors.Colormaps method), 151
M
make_image() (sage.plot.animate.Animation method), 164
Index 423
Sage Reference Manual: 2D Graphics, Release 8.8
N
ncols() (sage.plot.graphics.GraphicsArray method), 409
nrows() (sage.plot.graphics.GraphicsArray method), 409
O
options() (sage.plot.primitive.GraphicPrimitive method), 411
P
parametric_plot() (in module sage.plot.plot), 48
plot() (in module sage.plot.plot), 55
plot() (sage.graphs.graph_plot.GraphPlot method), 282
plot() (sage.plot.graphics.Graphics method), 394
plot() (sage.plot.graphics.GraphicsArray method), 409
plot3d() (sage.plot.arc.Arc method), 314
plot3d() (sage.plot.arrow.Arrow method), 316
plot3d() (sage.plot.bezier_path.BezierPath method), 329
plot3d() (sage.plot.circle.Circle method), 335
plot3d() (sage.plot.disk.Disk method), 346
plot3d() (sage.plot.ellipse.Ellipse method), 349
plot3d() (sage.plot.graphics.Graphics method), 395
plot3d() (sage.plot.line.Line method), 350
plot3d() (sage.plot.point.Point method), 354
plot3d() (sage.plot.polygon.Polygon method), 359
plot3d() (sage.plot.primitive.GraphicPrimitive method), 411
plot3d() (sage.plot.text.Text method), 135
plot_loglog() (in module sage.plot.plot), 119
plot_semilogx() (in module sage.plot.plot), 119
plot_semilogy() (in module sage.plot.plot), 119
plot_slope_field() (in module sage.plot.plot_field), 252
plot_step_function() (in module sage.plot.step), 271
plot_vector_field() (in module sage.plot.plot_field), 252
PlotField (class in sage.plot.plot_field), 252
png() (sage.plot.animate.Animation method), 164
Point (class in sage.plot.point), 354
point() (in module sage.plot.point), 355
point2d() (in module sage.plot.point), 356
points() (in module sage.plot.point), 358
polar_plot() (in module sage.plot.plot), 125
Polygon (class in sage.plot.polygon), 359
polygon() (in module sage.plot.polygon), 361
polygon2d() (in module sage.plot.polygon), 362
R
rainbow() (in module sage.plot.colors), 154
424 Index
Sage Reference Manual: 2D Graphics, Release 8.8
S
sage.graphs.graph_plot (module), 277
sage.plot.animate (module), 157
sage.plot.arc (module), 313
sage.plot.arrow (module), 315
sage.plot.bar_chart (module), 275
sage.plot.bezier_path (module), 328
sage.plot.circle (module), 334
sage.plot.colors (module), 147
sage.plot.complex_plot (module), 169
sage.plot.contour_plot (module), 177
sage.plot.density_plot (module), 244
sage.plot.disk (module), 344
sage.plot.ellipse (module), 348
sage.plot.graphics (module), 387
sage.plot.histogram (module), 272
sage.plot.hyperbolic_arc (module), 375
sage.plot.hyperbolic_polygon (module), 376
sage.plot.hyperbolic_regular_polygon (module), 382
sage.plot.line (module), 350
sage.plot.matrix_plot (module), 307
sage.plot.misc (module), 413
sage.plot.plot (module), 1
sage.plot.plot_field (module), 252
sage.plot.point (module), 354
sage.plot.polygon (module), 359
sage.plot.primitive (module), 411
sage.plot.scatter_plot (module), 270
sage.plot.step (module), 271
sage.plot.streamline_plot (module), 263
sage.plot.text (module), 135
save() (sage.plot.animate.Animation method), 165
save() (sage.plot.graphics.Graphics method), 395
save() (sage.plot.graphics.GraphicsArray method), 409
save_image() (sage.plot.graphics.Graphics method), 396
save_image() (sage.plot.graphics.GraphicsArray method), 410
scatter_plot() (in module sage.plot.scatter_plot), 271
ScatterPlot (class in sage.plot.scatter_plot), 270
SelectiveFormatter() (in module sage.plot.plot), 25
set_aspect_ratio() (sage.plot.graphics.Graphics method), 396
set_axes_range() (sage.plot.graphics.Graphics method), 397
set_default() (sage.plot.animate.APngAssembler method), 160
set_edges() (sage.graphs.graph_plot.GraphPlot method), 299
set_legend_options() (sage.plot.graphics.Graphics method), 397
set_options() (sage.plot.primitive.GraphicPrimitive method), 412
Index 425
Sage Reference Manual: 2D Graphics, Release 8.8
T
Text (class in sage.plot.text), 135
text() (in module sage.plot.text), 137
tick_label_color() (sage.plot.graphics.Graphics method), 407
to_float_list() (in module sage.plot.plot), 135
to_mpl_color() (in module sage.plot.colors), 156
U
unify_arguments() (in module sage.plot.misc), 415
X
xmax() (sage.plot.graphics.Graphics method), 408
xmin() (sage.plot.graphics.Graphics method), 408
xydata_from_point_list() (in module sage.plot.plot), 135
Y
ymax() (sage.plot.graphics.Graphics method), 408
ymin() (sage.plot.graphics.Graphics method), 408
426 Index