Contents Previous Next Index

12 Graphics


Maple offers a variety of ways to generate 2D and 3D plots. This chapter shows you how to create and manipulate such plots programmatically. You will learn about the Maple plotting library, the plot data structure, and how to write your own graphics procedures.

12.1 In This Chapter


•

Avoiding Common Problems



12.2 Introduction



Plots in Maple


A plot in Maple is a 2D or 3D graphical representation of a mathematical object, such as a function or a set of statistical data. In most of this chapter, we will be assuming a Cartesian coordinate system. We will generally refer to the horizontal and vertical axes in 2D plots as the and axes, respectively, while the axes in 3D plots will be called the , , and axes.
The following command generates a 2D plot of the function over the range 2 to 2.
>

plot(x^3x^2+3, x=2..2, 'title'="A First Plot");

The plot command is commonly used to create 2D plots and it is described in more detail in Generating 2D and 3D Plots. There is a corresponding plot3d command for creating 3D plots. In the previous statement, the three arguments to the plot command are the Maple expression x^3x^2+3 representing the function to be plotted, an equation specifying the plotting variable and range, and an option indicating that a title be added.
If you are using Maple's Standard Interface, executing the previous statement produces a plot in the current document. You can also create plotting output for other interfaces (for example, plots that open in a different window) and plots that are saved as a graphics file. For more information, see Interfaces and Devices.


Generating a Plot


The plot and plot3d commands are not the only ways to generate plots. Maple has an extensive library of commands for plotting and related tasks. These are described in The Plot Library. A plot that is generated with a library command is returned as a plot data structure. This is described in the section Data Structures.
Maple also provides interactive ways to create and modify plots, including:
•

the Interactive Plot Builder,

•

dragging and dropping, and

More information about these topics can be found in the Maple User Manual. If you are interested in simply creating a plot to be displayed in a Maple worksheet, then these easytouse, interactive methods are recommended. However, if you want to write programs that build and manipulate plots, then it is necessary to be familiar with Maple's plotting library commands.
Plots can also be used as embedded components, which means they are created as graphical interface components that can be manipulated through various actions. For more information, see Programming Interactive Elements



12.3 The Plot Library


This section provides an overview of the most commonly used plotting commands in the library. Refer to the Maple Plotting Guide (Help > Manuals, Resources, and more > Plotting Guide) for a pictorial listing of the kinds of plots that can be generated in Maple. The commands described here can be entered in the worksheet to generate individual plots, or they can be used in combination within procedures.
Many of the commands introduced in this section are from the plots package, so we will make the short form of the names available.
 (1) 
Most plotting commands accept optional arguments that change the default look of the plots. These options are summarized on the plot/option and plot3d/option help pages, and the most commonly used ones are described in Customizing Plots. We will refer to options that apply to the entire plot, such as title or gridlines, as global options. Options that apply to individual elements, such as color, are called local options.

Generating 2D and 3D Plots



Introduction


There are two basic plotting commands in Maple: plot and plot3d. The plot command produces 2D curves from representations of mathematical functions in one independent variable, and the plot3d command generates 3D surfaces from representations of functions in two variables.
The following command generates a 2D plot of the function over the range 1 to 5.
>

plot(exp(x/2)5*x+x^2, x=1..5, 'color'="NavyBlue", 'thickness'=2);

The following command generates a 3D plot of the function over and ranges of to .
>

plot3d(sin(x)*sin(y), x=Pi..Pi, y=Pi..Pi, 'transparency'=0.2);

In both these statements, the first argument is an expression representing the curve or surface to be plotted. This is followed by ranges for the independent variables. Finally, optional arguments may be added.


Expression and Operator Forms


The two plotting statements in the previous section use the expression form of the plot and plot3d commands. These plots can also be generated using the operator form of the calling sequence.
>

plot(proc(x) exp(x/2)5*x+x^2 end proc, 1..5, 'color'="NavyBlue", 'thickness'=2);

>

plot3d((x, y)>sin(x)*sin(y), Pi..Pi, Pi..Pi, 'transparency'=0.2);

In the operator form of the calling sequence, the first argument must be a procedure. It can be written using proc ... end proc, as in the call to plot or with arrow notation, as in the call to plot3d. It can be the name of any predefined procedure, including ones from the Maple library, as in the following example.
>

plot3d(binomial, 0..5, 0..5);

The procedure must accept one floatingpoint input argument in the 2D case and two such arguments in the 3D case, and it must return a floatingpoint value. For the operator form of the calling sequence, the range arguments are simple ranges rather than equations, as with the expression form of the calling sequence.
The operator form is primarily used when the function to be plotted is not easily written as a Maple expression in the plotting variables.
>

p := proc(x)
if abs(x)<0.1 then
100*x
elif abs(x)>0.5 then
4*x
else
1/x
end if;
end proc:

Normally, ranges given to a plotting command must have endpoints that evaluate to floatingpoint numbers. However, you can get an infinity plot by including infinity as one of the endpoints. For more information, refer to the plot/infinity help page. With 3D plots, you can also use, in the range for one variable, an expression that depends on the other variable.
>

plot3d(x*y, x=1..1, y=x^2..x^2);

To display multiple curves or surfaces in a single plot, provide a list of expressions or procedures to the plot or plot3d command. With the plot command, the options that affect the look of an individual curve, such as color or thickness, also accept lists of values.
>

plot([sin(x), cos(x)], x=Pi..Pi, 'color'=["Niagara BlueGreen", "Niagara DarkOrchid"]);

If you want to generate a 3D plot containing three surfaces, you must add the option plotlist=true to distinguish this plot from a parametric plot, which is described in the next section.
Occasionally, users get unexpected results by mixing the two calling sequences. Common errors are described in Mixing Expression and Operator Forms


Parametric Form


In the previous examples, the first argument is used to calculate the value of the dependent variable as a function of the independent variable or variables. A parametric curve, where the and values are functions of a single parameter , can also be plotted by the plot command. Similarly, a parametric surface, where the , , and values are functions of two parameters and , can be plotted by the plot3d command.
To generate a 2D parametric plot, provide as the first argument a list containing three items: an expression for the value, an expression for the value, and an equation containing the parameter and its range.
>

plot([sin(t), cos(t), t=0..Pi]);

To generate a 3D parametric plot, provide as the first argument a list containing three expressions, for the , , and values respectively. Two additional arguments are required, each in the form of an equation containing one of the parameters and its range.
>

plot3d([s^2, cos(s), t*cos(t)], s=0..2*Pi, t=0..Pi);

Operator form can also be used with parametric plots. The two previous examples are written using operator form as follows. As with nonparametric plots, options may be added.
>

plot([sin, cos, 0..Pi], thickness=3, linestyle=dash);

>

plot3d([(s,t)>s^2, (s,t)>t*cos(s), (s,t)>cos(t)], 0..2*Pi, 0..Pi, 'axes'='boxed');

The calling sequences for parametric plots are explained in detail on the plot/details and plot3d help pages.



Plotting Points, Polygons, and Text



Points


The plots:pointplot and plots:pointplot3d commands are used to plot collections of 2D or 3D points. These points can be provided as lists of twoelement or threeelement lists. Alternatively, they can be provided as two or three Vectors. The options symbol and symbolsize, described on the plot/options help page, can be used to change the look of each point.
>

pointplot([[0, 1], [1, 1], [3, 0], [4, 3]], 'color'= ["Red", "Green", "Black", "Blue"], 'symbol'='asterisk', 'symbolsize'=15, 'view'=[1..5, 4..2]);

>

xvector := <1, 2, 3, 4, 6>:
yvector := <1, 3, 5, 8, 9>:
zvector := <0, 1, 0, 1, 0.5>:
pointplot3d(xvector, yvector, zvector, 'color'="Niagara Burgundy", 'axes'='boxed', 'symbol'='solidsphere', 'symbolsize'=20);

The plot command also offers a calling sequence in which a collection of points is provided. The plot command differs from the pointplot command in that a connecting line is drawn by default. To draw discrete points with the plot command, use the style=point option.
If you have a large data set, it is highly recommended that you create the data set as a Matrix with the datatype option set to float. You can import data sets created by applications other than Maple by using the ImportMatrix command or the ImportData assistant.


Polygons and Polyhedra


The plots:polygonplot and plots:polygonplot3d commands plot polygons in 2D or 3D space. The vertices of the polygons are specified in a way similar to the way points are specified for the pointplot and pointplot3d commands.
>

polygonplot3d(Matrix([[0, 1, 1], [1, 1, 2], [3, 0, 5], [1, 1, 1]], 'datatype'='float'), 'color'="Niagara BluishPurple", 'axes'='boxed');

The plots:polyhedraplot command can be used to display any of the polyhedra described on the plots/polyhedra_supported help page.
>

polyhedraplot([0, 0, 0], 'polytype' = 'dodecahedron', 'scaling' = 'constrained', 'orientation'=[76, 40]);

The polyhedraplot command makes use of the geometry and geom3d packages. Use these packages if you want to do more computations with geometric objects. These objects can be plotted with the geometry:draw and geom3d:draw commands.
The plottools package also offers commands to create geometric objects. The result of these commands is a plot data structure. For more information about this package, see Creating Plot Structures.


Text on Plots


Text can be added to plots with the title and caption options. Axis and tickmark labels can also be specified with the labels and tickmarks options. For details on specifying tickmarks, refer to the plot/tickmarks help page. The text can be a string, a Maple expression, or an unevaluated typeset call, which allows you to combine mathematical expressions and strings. The mathematical expressions are typeset as described in Typesetting.
>

plot(x^2, x=2..2, 'title'='typeset'("A plot of the function ", x^2));

The plots:textplot and plots:textplot3d allow you to create plots containing text objects at arbitrary locations. The first argument is a list consisting of the coordinate values followed by the text to be placed at the location defined by the coordinates. Common options used with the textplot and textplot3d commands include the font option, to change the font type and size, and the align option, to position the text relative to the coordinate values.
>

textplot([1, 2, f(x)], 'font'=['times', 20], 'align'='above');

Usually, text objects are displayed in combination with other plot elements. In the next section, you will learn how to merge plots created with the commands introduced so far.



Combining Plots


This section describes how to use the plots:display command to combine plots, or more specifically, plot data structures. Two or more plots can be merged into a single plot or they can be placed sidebyside in a tabular arrangement.
When a plot is generated using any library command, a plot data structure is created. This structure can be assigned to a variable to be reused or modified. A detailed explanation of how the structures are formed is available in Data Structures, but it is not necessary to understand the details in order to manipulate the structures as described here.

Merging Plots


To combine the elements of two or more plots into a single plot, use the plots:display command, with the plots contained in a list as the first argument.
>

sinecurve := plot(sin(x), x=Pi..Pi):

>

maxtext := textplot([Pi/2, 1, "maximum"], 'align'='above'):

>

display([sinecurve, maxtext], 'caption'="This plot shows a local maximum of the sin function.");

Any combination of plot structures created from arbitrary Maple plotting commands can be combined using the display command, with a some restrictions. Usually, different types of plots (2D, 3D, arrays of plots, and animations) cannot be mixed.
When plots are merged, their options are also merged if possible. If there is a conflict, the display command will try to resolve it. For example, if two plots with different titles are merged, the display command will arbitrarily choose one for the merged plot.
The display command allows additional options to be provided. In the case of global options (ones that apply to the entire plot such as caption), these additional options will override those given for the individual plots. However, local options specified within the plots are generally not overridden.
The display command accepts the option insequence=true, which causes the plots to be displayed sequentially in an animation rather than merged. This use of the display command is discussed in Animations.


Generating an Array of Plots


The display command can be used to generate a tabular display of plots by providing a onedimensional or twodimensional Array of plot structures as the first argument. An animation plot structure can also be given, in which case the frames of the animation are displayed in tabular form.
Unlike the situation where plots are merged, you can mix different types of plots in an array of plots. For example, you can create an array containing both 2D and 3D plots.
A limited number of options can be passed to this command. Most global plot options are accepted and are applied to each plot in the Array individually.
For more information about this feature, including the aligncolumns option that allows you to align the axes of plots within a column, refer to the plot/arrayplot help page.



Specialty Plots


In this section, a few commonly used commands for specialty plots are introduced. Refer to the Maple Plotting Guide for a complete list of commands available.
The plots:implicitplot and plots:implicitplot3d commands generate plots of implicitly defined curves and surfaces.
>

implicitplot(x^2y^2 = 1, x = Pi .. Pi, y = Pi .. Pi, 'color'="Niagara BluishPurple", 'thickness'=2, 'gridrefine'=2);

The plots:contourplot command generates a contour plot for an expression in two variables. The plots:contourplot3d command does the same but generates a 3D display.
>

contourplot3d(5*x/(x^2+y^2+1), x=3..3, y=3..3, 'filledregions'=true, 'coloring'=["Niagara Burgundy", "Niagara Navy"]);

The plots:polarplot command generates a plot in polar coordinates with polar axes. This command offers a number of options to control the look of the radial and angular axes.
>

polarplot(theta, theta = 0..2*Pi, 'axis'['radial']=['color'="Niagara DeepBlue"]);

To plot in other coordinate systems, you can use the coords option. However, unlike with the polarplot command, these plots are drawn with Cartesian axes. For a complete list of supported coordinate systems, refer to the coords help page,
>

plot3d(z, theta=0..2*Pi, z=1..1, 'coords'='cylindrical');

The plots:dualaxisplot command creates a plot with two axes located at the left and right sides of the plot. You can provide either two expressions or two plot data structures.
>

dualaxisplot(plot(x^2, x=0..10, 'labels'=[x, x^2], 'legend'=x^2), plot(x^3, x =0..10, 'color'="Niagara Navy", 'labels'=[x, x^3], 'legend'=x^3), 'title'="A Comparison");

The plots:densityplot command creates a plot of a function of two variables colored by the function value. You can create a grayscale or RGBcolored plot.
>

densityplot(sin(x+y), x=1..1, y=1..1);

The plots:fieldplot and plots:fieldplot3d commands generate plots of 2D or 3D vector fields.
>

fieldplot3d([(x, y, z)>2*x, (x, y, z)>2*y, (x, y, z)>1], 1..1, 1..1, 1..1);



Other Packages


Many of the plotting commands introduced so far are part of the plots package. Several other packages in Maple also contain visualization commands.
The plottools package includes commands for generating and transforming graphical objects. This package is described in Creating Plot Structures.
The Student package consists of several subpackages designed to assist with the teaching and learning of mathematics. Each Student package has a collection of visualization commands. For example, for Calculus, refer to the Student/Calculus1/VisualizationOverview help page.
>

Student:Calculus1:RollesTheorem(sin(x), x=1..3*Pi1);

The Statistics package contains a large number of commands for visualizing univariate and multivariate data. These are listed in the Statistics/Visualization help page.
>

chartvalues := [seq(i=sqrt(i), i=1..15)]:
Statistics:PieChart(chartvalues, sector=0..180);

As mentioned in Polygons and Polyhedra, geometric objects can be created and displayed with the geometry and geom3d packages.
In the GraphTheory package, directed and undirected graphs can be drawn with the GraphTheory:DrawGraph command. In addition, the package provides many predefined graphs as well as visualizations of some algorithms.
>

with(GraphTheory):
with(SpecialGraphs):
DrawGraph(PetersenGraph());




12.4 Programming with Plots


Now that you are familiar with the wide range of commands available in the Maple plotting library, you can combine them to create custom graphics procedures. In this section, you will examine two simple examples: one in 2D and one in 3D. In later sections, additional programming examples will be provided as new concepts are introduced.

A 2D Example


This first example shows how plotting commands can be combined to create a single plot.
>

f := x*sin(x):
fderiv := diff(f, x):
fplot := plot(f, x=2*Pi..2*Pi, 'color'="Niagara Burgundy", 'legend'=f, 'thickness'=2):
fdplot := plot(fderiv, x=2*Pi..2*Pi, 'color'="Niagara Navy", 'legend'=fderiv):

>

plots:display([fplot, fdplot], 'title'="A function and its derivative", 'titlefont'=["Helvetica", 16]);

You can make this code more general and reusable by defining a procedure to produce a similar plot given an expression as the first argument, and an equation involving the plotting variable and range as the second argument.
>

derivativeplot := proc(f, r :: name=range)
local fderiv, v, fplot, fdplot;
# Extract the plotting variable and compute derivative.
v := lhs(r);
fderiv := diff(f, v);
# Create both curves.
fplot := plot(f, r, 'color'="Niagara Burgundy", 'legend'=f, 'thickness'=2):
fdplot := plot(fderiv, r, 'color'="Niagara Navy", 'legend'=fderiv):
# Combine into final plot.
plots:display([fplot, fdplot], 'title'="A function and its derivative",
'titlefont'=["Helvetica", 16]);
end proc:

>

derivativeplot(t^34*t^2+2*t, t=3..3);

There are a few modifications that can be made to improve derivativeplot, such as errorchecking and processing of additional plotting options.
In the derivativeplot procedure, the name=range type is specified for the r parameter, and the typechecking of this argument is done automatically by the builtin parameter processing facilities in Maple. However, it is useful to check for correctness of the first expression. Specifically, derivativeplot should check that the first argument is an expression in one variable and that variable matches the one given in the second argument. For example, the following incorrect call would produce an empty plot.
>

derivativeplot(x^34*x^2+2*x, t=3..3);

Many visualization commands in the Maple library that use the basic plotting procedures plot, plot3d, and plots:display assume that additional arguments are global plot options to be passed along for processing by these commands. In the modified derivativeplot procedure below, the unprocessed arguments in _rest are passed to the display command. For more information on _rest, see Special Sequences for Referring to Parameters and Arguments.
Here is the new derivativeplot procedure.
>

derivativeplot := proc(f, r :: name=range)
local fderiv, vnames, v, p1, p2, pfinal;
# Extract the plotting variable, check that it matches the
# indeterminate names in f, and then compute derivative.
v := lhs(r);
vnames := select(type, indets(f), 'name');
if nops(vnames)>1 then
error "too many variables in expression %1", f;
elif nops(vnames)=1 and vnames[1]<>v then
error "variable in expression %1 does not match %2", f, v;
end if;
fderiv := diff(f, v);
# Create both curves.
p1 := plot(f, r, 'color'="Niagara Burgundy", 'legend'=f, 'thickness'=2):
p2 := plot(fderiv, r, 'color'="Niagara Navy", 'legend'=fderiv):
# Combine into final plot.
plots:display([p1, p2], 'title'="A function and its derivative",
'titlefont'=["Helvetica", 16], _rest);
end proc:

>

derivativeplot(x^34*x^2+2*x, x=3..3, 'axes'='boxed', 'title' = "My latest plot");

Notice that the title option in the last derivativeplot call replaces the default title specified within the procedure. The convention followed by many Maple commands is that, when there are duplicate option names in the calling sequence, the last value given is the one that is applied. However, if you added the option color="Green", that would not change the default colors of the two curves. That is because the color="DarkRed" and color="Navy" options have been saved in the plot data structures p1 and p2 as local options, and they will not be overridden by plot options passed to the display command.


A 3D Example


The next example defines a procedure that accepts a list of expressions in one variable and displays these as "ribbons" in a 3D plot.
The following ribbonplot procedure accepts a list of expressions in one variable, an equation containing the variable name and range, and an optional keyword parameter, numberpoints. The numberpoints option specifies the number of points along the ribbon and is set to 25 by default. For brevity, this procedure does not include the errorchecking of the list of expressions as for the derivativeplot example.
>

ribbonplot := proc(f::list, r::name=range, {numberpoints::posint := 25})
local i, p, y, n;
n := nops(f);
p := Vector(n);
# Generate a 3D plot for each expression and combine with
# plots:display.
for i to n do
p[i] := plot3d(f[i], r, y=i0.75..i, 'grid'=[numberpoints, 2]);
end do;
plots[display](convert(p, 'list'), _rest);
end proc:

In the procedure ribbonplot, a Vector is used to store the n plot structures generated by the plot3d command. The grid option is passed to plot3d to specify the number of sample points in each plot direction. As with the previous example, additional global plot options are passed directly to the plots:display command.
Call ribbonplot with four expressions as the input and using the default options. Then, call it again with more sample points and constrained scaling.
>

ribbonplot([cos(x), cos(2*x), sin(x), sin(2*x)], x=Pi..Pi);

>

ribbonplot([cos(x), cos(2*x), sin(x), sin(2*x)], x=Pi..Pi, 'numberpoints'=40, 'scaling'='constrained');

Now, change the ribbonplot procedure so that it accepts input in operator form instead of expression form. Following the convention of the plot and plot3d command, in the modified procedure, the second argument is the plotting range, with no plotting variable specified. In addition, this version of ribbonplot allows a ribboncolors option that lets the user specify the color of each ribbon. If no such option is provided, the ribbons are colored with the default surface shading for 3D plots.
>

ribbonplot := proc(f::list, r::range, {numberpoints::posint := 25,
ribboncolors::list({name,string}):=[]})
local i, p, y, n, nr;
n := nops(f);
p := Vector(n);
# Check that the number of ribbon colors matches the number of
# procedures.
nr := nops(ribboncolors);
if nr>0 and nr<>n then
error "%1 ribbon colors needed", nr;
end if;
# Generate a 3D plot for each procedure and combine with
# plots:display. Include a ribbon color if provided.
for i to n do
p[i] := plot3d((u,v)>f[i](u), r, i0.75..i, 'grid'=[numberpoints, 2],
`if`(nr=0, NULL, 'color'=ribboncolors[i]));
end do;
plots[display](convert(p, 'list'), _rest);
end proc:

This procedure contains a check to ensure that the number of ribbon colors is the same as the number of procedures in the list f. Also, each procedure in f must be turned into a procedure with two input parameters before being passed to the plot3d command. In the call to plot3d, the color option is passed only if the ribboncolors option had originally been provided.
>

g := proc(x) if x < 0 then cos(x) else cos(2*x); end if; end proc:
ribbonplot([g, sin, cos+sin], Pi..Pi, 'transparency'=0.5,
'ribboncolors'=["DarkBlue", "DarkRed", "DarkGreen"]);




12.5 Data Structures


When you generate a plot in Maple, a plot data structure is created. The data structure is in the form of an unevaluated PLOT, PLOT3D, or _PLOTARRAY function call. The function arguments specify the objects to be plotted, as well as properties such as color or line thickness.
>

PLOT(POINTS([0., 0.], [1., 1.]), SYMBOL(_SOLIDBOX, 20));

These structures are Maple expressions; therefore, they can be assigned to variables and used in the same way as other expressions. When you enter a plotting command, the plot data structure is generated. Then, the output displayed depends on the current interface or plotting device requested. If you are using the standard worksheet interface and the plot output has not been redirected to a nondefault device, you will see the plots rendered as they are shown in this guide.
In this section, you will learn about the components of the plot data structure and the tools available to manipulate them. An understanding of the internal data structure is useful when writing programs that create and transform plots. However, it is strongly recommended that you use the available Maple library commands to generate plots and plot components whenever possible, rather than building the structures directly. Because these structures are part of the internal representation of plots, new graphics features offered in future Maple releases may necessitate minor updates to the format.

Types of Data Structures


This section provides an overview of the major components in plot data structures. Full details are available in the plot/structure help page. Note that some data structure names, those introduced in Maple 10 or later versions, are prefixed with underscores.

Basic Structures


•

PLOT  2D plot. Contains any of the object data structures listed below, except for MESH and ISOSURFACE, followed by any number of 2D option structures. Can also contain an ANIMATE structure.

•

PLOT3D  3D plot. Contains any of the object data structures listed below, followed by any number of 3D option structures. Can also contain an ANIMATE structure.

•

_PLOTARRAY  Array of plots. Contains a single Matrix, each element of which is a PLOT or PLOT3D structure.

•

ANIMATE  Animation. Contains a sequence of lists, each corresponding to a single frame in the animation and containing object and option structures.



Object Structures


In the following description, refers to the dimension (2 or 3) of the plot object.
A collection of points in dimensions is specified as a list of element sublists or as an by Matrix. Each sublist or Matrix row holds the coordinates of a single point.
•

CURVES  2D or 3D curve(s). Contains one or more collections of points in list or Matrix format as described above. Each collection of points defines a single curve.

•

POLYGONS  2D or 3D polygon(s). Contains one or more collections of points in list or Matrix format, each defining the vertices of a single polygon.

•

POINTS  2D or 3D points. Contains a collection of points in list or Matrix format.

•

TEXT  2D or 3D text object. Contains a point in list format followed by the string or expression to be displayed.

•

GRID  3D surface over a regular grid. Contains ranges in the and directions, followed by a twodimensional Array or list of lists containing the grid data.

Each object structure may contain one or more local option structures following the required data. For example, the following structure produces two polygons, one blue and one purple.
>

PLOT(POLYGONS([[0., 0.], [0., 1.], [1., 1.], [1., 0.]], COLOR(RGB, 0., 0., 1.)), POLYGONS([[1., 1.], [1., 2.], [2., 2.], [2., 1.]], COLOR(RGB, .5, 0., .5)));



Option Structures


There are a large number of option structures, some used for either 2D plots or 3D plots only, and some that apply to both. Most of the option structures have a direct correspondence to plot options described on the plot/options and plot3d/option help pages. (Note that the converse is not necessarily true. Several plot options do not have associated option structures.) Here are a few examples.
•

The symbol=asterisk option is translated to SYMBOL(_ASTERISK) in the plot data structure.

•

The color="Turquoise" option is translated to COLOUR(RGB, 0.25098039, 0.87843137, 0.81568627).

•

The title="Another Plot" and titlefont=["Helvetica", 30] options together translate to TITLE("Another plot", FONT("Helvetica", 30)).

In The Plot Library, the concept of global options (options that apply to the entire plot) and local options (ones that apply to a particular plot object) was introduced. This concept applies in a similar way to plot structures. Local option structures, such as STYLE or TRANSPARENCY can appear inside one or more plot object structures (CURVES, TEXT, etc.). Global option structures, such as TITLE, appear outside the plot object structures and usually there is only one instance of each kind of structure.
Some options, such as COLOR, can appear as a global option as well as a local option. In this situation, the value of the local option is applied to the plot object with which it is associated, and it is not overridden by the global option. If a plot structure has duplicate options at the same level (all global, or all local within the same plot object structure), such as two CAPTION entries, then the last one appearing in the structure is the one that is applied when the plot is rendered.
The plots:display command can be used to merge plot data structures. Details on how option structures are combined are given in Merging Plots. The display command can also be used to add an option structure to an existing plot. In the following example, the display command accepts the thickness=3 plot option and adds THICKNESS(3) to the data structure.
>

p := plot(x^22*x+1, x=4..4, 'color'="Niagara DarkOrchid"):

>

plots:display(p, 'thickness'=3);




Creating Plot Structures


Complete plot structures are normally created with commands such as the ones in the plots package. If you want to generate data structures for individual plot objects, it is recommended that you use the commands in the plottools package rather than build them yourself.
The plottools commands do not produce complete plots, so the output will consist of the data structure in text form rather than a rendered image. To view the result of a plottools command, you must pass it to the plots:display command.
>

t := torus([1, 1, 1], 1, 2, 'color'="LightBlue", 'transparency'=.5):

>

s := sphere([5, 2, 3], 2, 'color'="LightGreen", 'transparency'=.7):

>

plots:display([t, s], 'scaling'='constrained');

As shown in this example, options may be passed to the plottools commands. These must be local options that are applicable to the type of structure that is produced. The color option applies to any plot object, while the transparency option is used only with plot objects that are rendered as surfaces. The scaling option is a global option that applies to an entire plot; thus, it is included in the call to display instead of the calls to torus and sphere.


Altering Plot Structures


In addition to the commands for building plot structures, the plottools package also contains commands for altering structures. These commands, which accept 2D or 3D plots as input, include ones for translation, scaling, and rotation of a plot.
>

p := plots:arrow([0,1], 'color'="Orange"):

>

plots[display]([p, pr], 'scaling'='constrained', 'axes'='boxed');

You can apply an arbitrary transformation to a 2D or 3D plot using the plottools:transform command. To do this, define a procedure f that represents a mapping from to , where and can take values 2 or 3. The procedure must take as input arguments and return a list of components. If you pass f to the transform command, it returns a procedure that takes a 2D or 3D plot data structure as its argument and returns a transformed plot.
>

p := plots:contourplot(2*x^2+y^2, x=3..3, y=3..3, 'filled', 'coloring'=["Purple", "Teal"]):

>

f := (x, y)>[x, y, 0]:

>

plots:display(tf(p), 'axes'='boxed', 'view'=['default', 'default', 2..2], 'scaling'='constrained');




12.6 Customizing Plots


In this section, you will look at different ways of customizing plots by providing options to the Maple plotting commands. The complete list of options is available in the plot/options and plot3d/option help pages. Here, a few of the more commonly used ones are described.
In the descriptions in this section, it is assumed that you are using the plot and plot3d commands. However, many other plotting commands in Maple accept these options as well.

Controlling the Sampling


The commands for plotting curves and surfaces generate points by sampling the function to be plotted over the specified range or ranges. Several options are available to control how the sampling is done. All these options must be provided when the curve or surface is first created. They cannot be used with the plots:display command or with the plottools commands that alter existing plot structures.

Number of Points


The numpoints option sets the minimum number of sampling points used by the plot and plot3d commands. Because the plot command uses an adaptive plotting scheme, it usually generates more points than this number. The plot3d command does not use an adaptive scheme and generates a number of points close to the specified numpoints value.
The grid option is an alternative way of specifying the number of sample points in 3D plots. This option takes a list of two positive integers that specify the dimensions of the rectangular grid over which the points are generated.
>

p1 := plot3d(.5*sin(x+y), x = Pi .. Pi, y = Pi .. Pi, grid = [10, 10]):

>

p2 := plot3d(.5*sin(x+y)+1, x = Pi .. Pi, y = Pi .. Pi):

>

p3 := plot3d(.5*sin(x+y)+2, x = Pi .. Pi, y = Pi .. Pi, grid=[40, 40]):

>

plots:display([p1, p2, p3]);



Adaptive Plotting


In 2D plotting, the numpoints value is used to set the initial sample points. When the adaptive option value is set to true (the default value), the intervals defined by the initial sample points are further subdivided in an attempt to get a better representation of the function. The attempts at subdivision are based on the current sample values, and intervals are subdivided a maximum of six times. The adaptive option can also take a positive integer value that controls the maximum times intervals are subdivided.
If the adaptive option is set to false, the number of points generated is the same as the numpoints value (or the default value, if it is not provided).
The sample option allows you to provide a set of points at which the function is to be sampled. If adaptive plotting is allowed, the final set of sample points includes those in the provided list but normally consists of many more. To use exactly the list of points given by the sample option, specify adaptive=false.
>

plot(x^2, x=0..4, 'adaptive'='false', 'sample'=[seq(0.1*i, i=0..40)], style=point);

The adaptive and sample options are not available for 3D plotting.


Discontinuities


If a function with a discontinuity is being plotted, then evaluation at the point of discontinuity will lead to an undefined value, which results in a gap in the plotted curve or surface. It is more likely that the function is evaluated at points very close to the discontinuity, and this can lead to a distorted view of the plot when the values are extremely large or small and an inappropriate connecting of the points over the discontinuity.
In the 2D case, the discont option can be used with the plot command when you suspect a discontinuity. The plot command uses the discont and fdiscont commands to detect discontinuities and divides the plotting range into subranges over which the plot is continuous. In the following example, the plot on the left contains extraneous vertical lines. These are avoided in the righthandside plot generated with the discont option.
>

plots:display(Array([plot(tan(x), x=Pi..Pi, y=4..4), plot(tan(x), x=Pi..Pi, y=4..4, 'discont'=true)]));

Usually, removable discontinuities are ignored. However, you can use the showremovable suboption to draw a circle on the plot to mark the point of discontinuity. Another suboption is usefdiscont, which controls how the fdiscont command is used to find discontinuities numerically. For more information about all the suboptions available for the discont option, refer to the plot/discont help page.



Colors


The color option is used to specify the color of plot objects in 2D and 3D plots, and its value can take several forms. A few of these are described in this section. For more details, refer to the plot/color help page. Default colors are chosen by Maple when none are specified.

Specifying a Single Color


The easiest way to apply a color to a plot object is to provide the name of a color known to the Maple plotting commands. The list of all such color names and their associated RGB values is available on the plot/colornames help page. These names correspond to commonly used HTML color names.
>

plot3d(binomial, 0..5, 0..5, 'color'="Niagara GreenishBlue");

Alternatively, a plot color structure can be used as the value for the color option. This takes one of the following forms: COLOR(RGB, v1, v2, v3), COLOR(HSV, v1, v2, v3), or COLOR(HUE, v1). More information about the COLOR structure is available in the plot/structure help page.


Using Multiple Colors


The color option can be applied to individual objects that are then combined using the plots:display command. Some commands, such as plot, allow you to provide a list of objects to be plotted as well as a list of colors to be applied in order.
>

plot([seq(i+sin(x), i = 1 .. 4)], x = 0 .. 4*Pi, 'color'= ["Niagara Navy", "Niagara Burgundy", "Niagara Olive", "Niagara PaleRed"]);

If no colors are provided, the plot command uses a default list of colors. To see the default list used by plot and several other 2D plotting commands, use the plots:setcolors command.
 (2) 
>

plot([seq(i+sin(x), i = 1 .. 4)], x = 0 .. 4*Pi);

The plots:setcolors command also allows you to set new default colors. If there are fewer colors than curves, the colors are repeated in order.
>

plots:setcolors(["Indigo", "ForestGreen"]):

>

plot([seq(i+sin(x), i = 1 .. 4)], x = 0 .. 4*Pi);

The following command resets the colors to the original default colors.
>

plots:setcolors('default'):



The ColorTools Package


The ColorTools package contains commands for working with colors and color palettes, as well as converting between supported color formats. For a complete list of ColorTools commands and supported color formats, see the ColorTools help page.


Coloring Surfaces


When you plot a 3D surface, the surface is shaded using a default shading scheme based on the coordinates of the points that define the surface. As with 2D plots, a single color can be provided through the color option. Alternatively, a different shading may be specified with the shading option.
>

plot3d(x^2*y, x=1..1, y=1..1, 'shading'='zgreyscale');

You can obtain a customized shading parametrized by the plot variables. To do this, provide an expression or a list of three expressions in terms ojf the plot variables. If a single expression is given, it is taken to be a hue value; if a list of three expressions is given, the triplet is taken to be RGB values.
>

plot3d(x^2*y, x = Pi/2 .. Pi/2, y = 1 .. 1, color = y^2*cos(x));

Similarly, if the input is given as procedures instead of expressions in two plotting variables, the color can be specified by a procedure or a list of three procedures that take two input parameters and return a single value. More details are provided in the plot3d/colorfunc help page.
The colorscheme option is another way of coloring either a 3D surface or a density plot generated by the plots:densityplot command. This option allows you color a surface based on a function value or to supply your own procedure implementing a color scheme. More details are given in the plot/colorscheme help page.
>

plots:densityplot(x*cos(x)+y^2, x=5..5, y=5..5, colorscheme=["Green", "Violet", "NavyBlue"], style=surface);



Images and Backgrounds


Surfaces can be colored with an image using the image option, as described in the plot3d/options help page.
>

imgfile := cat(kernelopts(mapledir), "/data/images/rollercoaster.jpg"):

>

plot3d(sin(y)*cos(x), x=0..Pi, y=0..Pi, image=imgfile, lightmodel=none, orientation=[0, 80, 30]);

You can also use an image as a background for a 2D plot by providing the background=t option where t is an image file or filename. The background option also allows you to use a solid color as the plot background. See the plot/options help page for more information.
>

plot(sin(x), color="Orange", background="DarkBlue", thickness=3, axis=[color="LightGrey"]);




Size and View


The size option, for 2D plots only, allows you to specify the size of the plot window. The size is usually specified in numbers of pixels but an aspect ratio or fraction of the worksheet width may be provided. In the following example, the width is specified as 300 pixels and the height as 1.5 times the width.
>

plot(x^2, x = 0 .. 2, size = [300, 1.5]);

The view option determines the extent of the axes in the rendered plot. In the next example, the plot data structure produced by the plot command contains all the points generated from the given range, 2..4. However, the view is restricted to the portion of the plot in the box defined by values in the range 1..3 and values in the range 3..0.
>

plot(x^2+2*x1, x=2..4, 'axes'='boxed', 'thickness'=3, 'view'=[1..3,3..0]);

In the next example, the specified axis view is much larger than the range. Since the computed points are based on the range , the displayed curve is only shown for this range. To generate the curve for the entire range from 5 to 7, you must reexecute the plot with x=5..7 as the second argument.
>

plot(x^2+2*x1, x=2..4, axes=boxed, thickness=3, view=[5..7, 10..2]);

In certain cases, the plotting command automatically sets the view option based on the provided ranges. Otherwise, the default view is determined by the minimum and maximum values of the data points generated.

smartview option


The plot command generates data based on the range provided by the user or on a default range, if the user does not provide range data. When the smartview=true option is provided, the view is restricted to the most important regions of the plot.
To prevent such a restriction use the smartview=false option.
For example:
>

plot(1/(x1),smartview=false);




Typesetting


Typeset text and mathematics can appear anywhere in a 2D or 3D plot where text is allowed. This includes text provided by the plots:textplot command and the following options: caption, labels, legend, tickmarks, and title.
You can provide arbitrary expressions to the textplot command or as values for the options to the command. These expressions are displayed on the plot as typeset output whenever possible. Strings are displayed as plain text without the quotation marks, but names such as x, y, and Pi are typeset. To concatenate several expressions, wrap them inside a typeset structure.
>

plot(x^2/(x+5), x=1..5, 'caption'='typeset'("A plot of ", x^2/(x+5), "."));

The plot/typesetting help page provides more details about using typeset mathematics in plots. It includes tips on using 2D math input to generate typeset expressions that are not easily expressed in 1D math input. These expressions can then be made into atomic identifiers through the context menu and then converted to 1D math to be used programmatically. For more information about 1D and 2D math input modes, see 2D Math.


Axes and Gridlines


Several options are available for customizing the look of axes and gridlines, including:
•

axes and axesfont for specifying the style of axes and the font for tickmark labels

•

labels and labelfont for adding labels to axes and specifying the font for the labels

•

gridlines for adding gridlines to 2D plots.

•

tickmarks for controlling the number of tickmarks or for specifying custom tickmarks and labels

>

plots:implicitplot([x^2y^2 = 1, y = exp(x)], x = Pi .. Pi, y = Pi .. Pi, 'color' = ["Blue", "DarkGreen"], 'axes' = 'boxed', 'tickmarks' = [3, 3], 'labelfont' = ["Times", 16]);

You can obtain greater control over the look of each axis by using the axis or axis[dir] option and providing a list of suboptions. To apply suboptions to one axis, use the indexed axis[dir] option, where the direction dir is 1, 2, or 3, with 3 applicable to 3D plots only. To apply the suboptions to all axes, use the axis option without the index.
The suboptions include gridlines and tickmarks options, which are similar to the regular options of these names but offer more flexibility. Other suboptions are color (to change the color of an axis), location (to move an axis to the lowest or highest value of the view range or to the origin), and mode. This last suboption allows you to use logarithmic scaling for an axis. (Note that you can also create log plots with the plots:logplot, plots:semilogplot, and plots:loglogplot commands.)
>

plot3d(x*y, x = 1 .. 10, y = 1 .. 10, 'axes' = 'normal', 'axis'[3] = ['mode' = 'log', 'color' = "Crimson"]);



Coordinate Systems


Plots are normally plotted in the Cartesian coordinate system, but you can use the coords option to plot in a different system. The 2D and 3D coordinate systems recognized by Maple and the transformations that they represent are listed in the coords help page.
>

plot3d(y, x=Pi..Pi, y=0..2*Pi, 'coords'='cylindrical');

The coords option must be used at the time the plot is generated. However, the plots:changecoords command can be used to transform a plot structure that has already been created to one that uses a different coordinate system.
When working with alternate coordinate systems, two useful commands are plots:coordplot and plots:coordplot3d, which provide graphical representations of coordinate systems using lines or surfaces of constant value.
>

plots:coordplot('rose', 'color'=["Blue", "Magenta"]);

Because the polar coordinate system is commonly used, Maple has a plots:polarplot command for plotting in this system. Polar axes are displayed by default, and special options are available for customizing the look of these axes. In particular, the coordinateview option can be used to restrict the view in the polar coordinate system.
>

plots:polarplot([[t, t, t = Pi .. Pi], [2*cos(t), sin(t), t = Pi .. Pi]], 'color' = ["DarkRed", "Brown"], 'axis'['angular'] = ['color' = "Navy"], 'coordinateview'=[0..4, 0..Pi]);

The style of the coordinate axes (either polar or cartesian) can be changed with the axiscoordinates option. This option is available for 2D plots in general and is not restricted to the polarplot command.
>

plot([s*sin(s), s*cos(s), s = 0 .. 4*Pi], 'axiscoordinates' = 'polar');



Setting Options


The section Colors describes the use of the plots:setcolors commands to set the default curve colors for 2D plots. More general commands for setting options for all 2D and 3D plotting commands are plots:setoptions and plots:setoptions3d.
The plots:setoptions command allows you to specify options that are applied to all 2D plots created in the same Maple session. The plots:setoptions3d command performs a similar function for 3D plots. These settings are recognized by the plot, plot3d, and plots:display commands, as well as a number of other plotting commands in Maple.
In the following example, the default symbol for point plots is set to solidcircle with a symbol size of 20.
>

plots:setoptions('symbol'='solidcircle','symbolsize'=20);

>

plots:pointplot([seq([i, i^2], i=0..10)]);

The default value is overridden in the following example, which provides the symbol option explicitly in a command.
>

plots:pointplot([seq([i, i^2], i=0..10)], 'symbol'='box');




12.7 Animations



Building an Animation with plots:display


The plots:display command can be used to build an animation. The calling sequence is
plots:display(L, insequence=true)



where L is a list of plot structures, all 2D or all 3D. An animation will be created in which the plots in L appear in sequence, one in each frame.
>

for i to 10 do
plotframe[i] := plot(0.75*x^i, x=0..1):
end do:
plots:display([seq(plotframe[i], i=1..10)], insequence=true, scaling=constrained);



The plots:animate command


The plots:animate command can be used to create an animation from a single command with one varying parameter. Any Maple plotting command that produces a 2D or 3D plot, including ones in packages not primarily intended for plotting, can be used.
The following example shows how to create an animation with the plots:spacecurve command. The first argument to animate is the procedure name. The second argument is the list of arguments to be passed the the given procedure. This list contains a parameter whose range, over which the animation will vary, is given in the final argument to animate.
>

plots:animate(plots:spacecurve, [[cos(t), sin(t), (2+sin(a))*t], t=0..20, 'thickness'=5, 'numpoints'=100, 'color'="Black"], a=0..2*Pi);

You can animate a custom procedure instead of a Maple library command.
>

p := proc (s, t) plots:display([plottools:disk([s*cos(s), s*sin(s)], 1, 'color' = "Orange"), plottools:disk([t*cos(t), t*sin(t)], 2, 'color' = "Blue")], 'scaling' = 'constrained') end proc:

>

plots:animate(p, [a, a+3*Pi], a=0..4*Pi);



3D Animations with the viewpoint Option


An animation can be generated from any static 3D plot with the viewpoint option. This option allows you to create the animation by varying the viewpoint through the plot, as if a camera were flying through the space. The position, direction, and orientation of the camera can be varied.
There are several ways to create the animation, which are all described on the plot3d/viewpoint help page. The simplest way is to use one of the standard viewpoint paths, such as circleleft.
>

plots:polyhedraplot([0, 0, 0], 'polytype'='OctagonalPrism', 'scaling'='constrained', 'viewpoint'='circleleft', 'lightmodel'='light3', 'glossiness'=1);

Another way is to provide a parametrically defined path.
>

plot3d(1, x = 0..2*Pi, y = 0..Pi, 'coords'='spherical', 'viewpoint'=['path'=[[50*t, 80*cos(t), 100*sin(t)], t=3*Pi..Pi]]);



Other Animation Commands


There are a number of other commands in Maple for creating animations, such as plots:animatecurve (for visualizing the drawing of a curve) and ones for specific applications such as those in the Student package.


Displaying an Animation as an Array of Plots


Animations, like other plots, can be combined using the plots:display command and put into arrays of plots. You can display an entire animation, frame by frame, in a table by passing it directly to the plots:display command.
>

anim := plots:animatecurve([sin(t), cos(t), t=0..2*Pi], 'thickness'=3, 'color'="Indigo", 'frames'=9):

>

plots:display(anim, 'view'=[1..1, 1..1], 'scaling'='constrained');

If you specify the insequence option to plots:display, then it is displayed as a regular animation.
>

plots:display(anim, 'view'=[1..1, 1..1], 'scaling'='constrained', 'insequence'=true);




12.8 Miscellaneous Topics



Efficiency in Plotting



The FloatingPoint Environment


The plotting commands attempt to evaluate the input expressions or procedures using the floatingpoint hardware of the underlying system whenever possible. This is done through calls to the evalhf command. If the environment variable Digits is greater than the value of evalhf(Digits), or if an initial attempt using evalhf fails, then the slower evalf command is used for numerical evaluation. For an introduction to the evalhf and evalf commands, see Maple Commands for Numerical Computing.
To maximize efficiency, expressions and procedures passed to plotting commands should be written so that they can be evaluated by evalhf if possible. For more information on the functions and constructs supported by evalhf, refer to the evalhf/procedure and evalhf/fcnlist help pages.


Lists and rtables


Plotting large datasets of points is much more efficient when you use rtables rather than lists. For instance, for efficiency, when using the plots:pointplot and plots:pointplot3d commands, provide the input as a Matrix of datatype float[8]. If your data is in an external file, it can be imported directly into a Matrix with the ImportMatrix command.
It is recommended that you build plot structures by using the commands in the plotting library. However, if you want to build the plot structures directly, similar guidelines apply. Most plot data structures (described in Data Structures) allow the data to be stored in either a list or an rtable. rtables should be used for those structures that support them, and they should be created with the datatype=float[8] and order=C_order options.



Interfaces and Devices


The Maple standard worksheet interface provides all of the functionality for plotting described in this chapter. If you are using another interface, then some of the plotting features will not be available. For more details about the differences, refer to the plot/interface help page.
With any of these interfaces, you can redirect plotting output to an alternative device. The devices available are listed in the plot/device help page and include common graphics formats such as JPEG and PostScript®.
Plot output is controlled by a number of interface variables such as plotdevice (the name of the plotting device) and plotoutput (the name of an output file). These are described in the interface help page. The plotsetup command provides a simpler way to set up these interface variables, without having to use the interface command directly.
For example, the following command specifies that all subsequent plot output be in PostScript format and be saved in a file called plot.ps. Furthermore, the PostScript driver will use a portrait orientation with no border. The plotsetup(default) command restores the default output options.
>

plotsetup('ps', 'plotoutput'="plot.ps", 'plotoptions' = "portrait,noborder");




12.9 Avoiding Common Problems



Mixing Expression and Operator Forms


If the first argument to a plotting command is an expression in the plotting variable, these same plotting variables must appear in the range arguments. A common mistake is to omit the plotting variable in the ranges or to use a different variable name accidentally. It is also a mistake to provide a procedure as the first argument but then to use variable names in the subsequent range arguments. The first example below generates an error, while the next one produces an empty plot with a warning that the plotting function could not be evaluated to numeric values.
Another common mistake is to use the expression form when you mean to provide an operator. A typical example is the following:
>

p := proc(x) if type(x, 'positive') then sqrt(x) else 0 end if; end proc;

 (3) 
The correct way to plot this procedure over the range 1 to 1 is the use operator form.
>

plot(p, 1..1, 'axes'='boxed');

If you attempt to use expression form, then p(x) is evaluated immediately, the value 0 is passed to the plot command as the first argument, and the resulting plot is a horizontal line.
>

plot(p(x), x=1..1, 'axes'='boxed');



Generating Nonnumeric Data


Most of the Maple plotting commands are meant to work with realvalued functions, though specialized commands such as plots[complexplot] are available for plotting complexvalued functions. Generally, when evaluation of the input expression or procedure results in a complex value, the value is replaced by an undefined value. Many plotting commands check for numbers with very small imaginary parts and will convert these numbers to real numbers, with the criteria for dropping an imaginary part depending on the Digits environment variable and on its relative size compared to the real part. This procedure helps to avoid problems caused by roundoff errors during the computation. However, it is advisable to ensure that the input expression or procedure always evaluates to a numeric value.
In the first example below, the ragged edge is caused by the fact that some of the values are undefined. The second example, which has the range of t going from 0 to s instead of 0 to 1, produces a more accurate plot.
>

plot3d(sqrt(s^2t^2), s=0..1, t=0..1);

>

plot3d(sqrt(s^2t^2), s=0..1, t=0..s);

Nonnumeric data can also be produced as the result of mistyping a variable name. In the example below, the second argument mistakenly contains the variable z instead of x. Consequently, when a numeric value in the range 0..Pi is substituted for the variable z in the expression sin(x), the result remains the algebraic expression sin(x), which is nonnumeric. This leads to a warning from Maple and an empty plot.



Contents Previous Next Index
