Mathematica Graphics

1. Overview of Basic Graphics Commands

Two-Dimensional Graphics

Plot

The simplest example of Mathematica’s graphing capabilities is a graph of a function of one variable created with Plot. Plot takes a function to be graphed and a domain for the variable, and generates a two-dimensional graph.

Plot[Sin[x]/x, {x, -10, 10}]

Plot also accepts a list of functions to plot on the same set of axes.

Plot[{Sin[x], Cos[x]}, {x, -π, π}];

Options

There are dozens of options we can use to control almost every aspect of a graph. Options[FunctionName] returns a list of the options available for a function, along with their default values.

Options[Plot]

For example, by default Mathematica uses an algorithm to choose the most “interesting” y-range for a graph. In the above list, we see that the default value for PlotRange is Automatic.

Plot[Sin[(x^2)]/(x^2), {x, -10, 10}];

We can override the default setting by giving a different value to the PlotRange option.

Plot[Sin[(x^2)]/(x^2), {x, -10, 10},  
      PlotRange -> {-0.25, 1.05}];

In every case, options are added after the required arguments to the function. We set an option by typing the name of the option, an arrow made by the two characters - and > (or the special character -> made by typing Esc->Esc), and the new value of the option. Note that most plotting commands have a similar set of options.

\(\(Plot[Sin[x]/x, \ {x, \(-10\), 10}, \ Frame -> True, \ 
      PlotLabel -> "sinc function", \ GridLines -> Automatic, \ 
      PlotRange -> {{\(-11\), 11}, {\(-0.5\), 1.15}}, 
	AspectRatio -> 1]; 
    \)\)

In the following sections we will change many of a graph’s default option settings.

ParametricPlot

ParametricPlot plots a two-dimensional curve described by two functions of the same parameter, one that describes movement in the x direction and one for the y direction. This allows us to plot curves that are not functions, in the mathematical sense. Here is a parametric plot of a circle.

ParametricPlot[{Sin[t], Cos[t]}, {t, 0, 2 π}];

The option AspectRatio controls the relative sizes of units on the two axes; the setting Automatic makes them equal (that is, makes one unit on the vertical axis equal to one unit on the horizontal axis).

ParametricPlot[{Sin[t], Cos[t]}, {t, 0, 2 π}, 
      AspectRatio -> Automatic];

ParametricPlot can be used to plot graphs of complicated curves that cannot be expressed as a function of two variables.

ParametricPlot[{4 Cos[-5 t/4] + 7 Cos[t], 
        4 Sin[-5 t/4] + 7 Sin[t]}, {t, 0, 8 π}, 
      AspectRatio -> Automatic];

ParametricPlot takes many of the same options as Plot.

ParametricPlot[{4 Cos[-11 t/4] + 7 Cos[t], 
        4 Sin[-11 t/4] + 7 Sin[t]}, {t, 0, 8 π}, 
      AspectRatio -> Automatic,  Axes -> False, Frame -> True, 
      FrameLabel -> {"x", "y"}];

ImplicitPlot

ImplicitPlot allows us to plot implicit relations, rather than functions. It is defined in one of the standard packages, so we must load it first with the Needs command.

Needs["Graphics`ImplicitPlot`"]

ImplicitPlot[eqn, {x, a, b}] draws a graph of the set of points that satisfy eqn. The variable x is associated with the horizontal axis and ranges from a to b. The remaining variable in the equation is associated with the vertical axis. We can also specify a vertical range for the graph using the form ImplicitPlot[eqn, {x, a, b}, {y, c, d}].

ImplicitPlot[3 (x^2) + 3 x y + 12 (y^2) == 12, {x, -2.5, 2.5}, 
      AxesOrigin -> {0, 0}];

Like most graphing functions, ImplicitPlot accepts a list of functions to plot on the same set of axes.

ImplicitPlot[{3 (x^2) + 3 x y + 12 (y^2) == 12, 
        12 (x^2) + 3 x y + 3 (y^2) == 12, 
        3 (x^2) + 12 x y + 3 (y^2) == 1}, {x, -2.5, 2.5}, {y, -2.5, 
        2.5}, AxesOrigin -> {0, 0}];

Graphics Directives and Plot Styles

Mathematica contains several objects called graphics directives, which specify the style in which a graph should be drawn. Graphics directives control the color, thickness, point size, and dashing of lines, points, and other objects.

For example, to specify that lines should be drawn with a specified thickness, we use the directive Thickness[t], where t is given as a percentage of the width of a graph.

All two-dimensional graphing functions have an option called PlotStyle, which allows us to specify a list of graphics directives that control how the actual curve (as opposed to the surrounding axes, grid lines, etc.) is drawn. To draw a sine wave so that the curve is drawn with a thickness 2% of the width of the graph, we set the option PlotStyle -> Thickness[0.02].

Plot[Sin[x], {x, -3, 3}, PlotStyle -> {Thickness[0.02]}];

To draw a curve with a dashed line, we use the directive Dashing. Dashing[{d}] draws a line so that it alternates between line segments d percent of the width of the graph and gaps d percent of the width of the graph. Dashing[{(Subscript[d, 1]),(Subscript[d, 2])}] alternates between line segments (Subscript[d, 1]) long and gaps (Subscript[d, 2]) long, and Dashing[{(Subscript[d, 1]),(Subscript[d, 2]),…}] applies the successive widths cyclically. The following graph uses line segments twice as long as the gaps.

Plot[Sin[x], {x, -3, 3}, PlotStyle -> {Dashing[{0.04, 0.02}]}];

There are several ways to specify colors using graphics directives. RGBColor[r,g,b] describes a color made up of r, g, and b percent of red, green, and blue, respectively. Thus, RGBColor[1,0,0] is red, and RGBColor[1,0,1] is purple. (The parameters r, g, and b must all be between 0 and 1.)

Other color functions are Hue[h], which represents the spectrum of colors going through red, orange, yellow, green, blue, purple, and back to red; and GrayLevel[g] (0 ≤ g ≤ 1), where GrayLevel[0] is black and GrayLevel[1] is white.

To change the style of each graph in a list given to Plot, we give a list containing as many graphics directives as there are functions being plotted. Here we draw the first curve in the list using a thick line (Thickness[0.02]), and the second curve using a green line (RGBColor[0,1,0]).

Plot[{Sin[x], Cos[x]}, {x, -3, 3}, 
      PlotStyle -> {Thickness[0.02], RGBColor[0, 1, 0]}];

To apply multiple styles to each function in a list, we surround the styles that apply to each function inside a set of list brackets.

Plot[{Sin[x], Cos[x]}, {x, -3, 3}, 
      PlotStyle -> {{Thickness[0.02], Hue[0.1]}, {Dashing[{0.04, 0.02}], 
            GrayLevel[0.5]}}];

One tricky case to be aware of is that in order to specify more than one graphics directive in the plot style of a single function, we must surround the graphics directives with the double list brackets {{ and }}.

\(\(Plot[Sin[x]/x, {x, \(-10\), 10}, 
	
      PlotStyle -> {{RGBColor[0, 0, 1], Thickness[0.015]}}]; \)\)

Combining Graphs

Show allows us to display a previously computed graph without having to recompute any of the points that make up the curve(s).

Show[graphics, options] displays two- and three-dimensional graphics using the new option settings specified. Show accepts options that affect the way a graph or its surrounding elements (axes, frame, etc.) is drawn, without requiring any points of the graph to be recomputed.

p1  =  Plot[ Sin[x]/x,  {x,  -10, 10}];

None of the options given below require points on the graph to be recomputed, so we can use them inside Show.

Show[p1, Frame -> True, AxesStyle -> Hue[0], 
      PlotRange -> {-0.1, 0.8}, PlotLabel -> "p1"];

When given a list of graphics, Show combines them onto the same set of axes. Here is another two-dimensional plot.

p2 = 
      Plot[BesselJ[2, x], {x, -10, 10}, 
        PlotStyle -> {GrayLevel[0.5]}];

We combine p1 and p2 by placing their names in a list and giving the list to Show.

Show[{p1, p2}];

Show also combines three-dimensional graphics. Here are two three-dimensional graphs.

\(p3 = Plot3D[1 - x, {x, 0, 1}, {y, 0, 1}, ColorFunction -> Hue]; 

    p4 = Plot3D[y, {x, 0, 1}, {y, 0, 1}, ColorFunction -> GrayLevel]; 
    \)

We put them in the same box using Show.

Show[{p3, p4}];

The object GraphicsArray takes an array of graphs, and when used with Show, displays the graphs in an array. Here is an array containing the four previous graphs.

Show[GraphicsArray[{{p1, p3}, {p4, p2}}]];

Exercises: Two-Dimensional Graphics

Make a simple two-dimensional plot of (x^2) - 20  cos((x^2)) between -10 and 10. (If there are obvious flaws in the graphic, plot it again using more plot points.)

Plot[(x^2) - 20 Cos[(x^2)], {x, -10, 10}];

Use Options[Plot] or the on-line help to find a list of all the options that Plot accepts. Plot the same function as above, this time changing at least five of Mathematica’s default options.

Plot[(x^2) - 20 Cos[(x^2)], {x, -10, 10}, PlotPoints -> 75, 
      Frame -> True, GridLines -> Automatic, 
      PlotLabel -> "Exercise One", AspectRatio -> 0.5];

Three-Dimensional Graphics

Plot3D

Plot3D is the three-dimensional analog of the Plot command. Given a function of two variables and a domain for each variable, Plot3D produces a surface plot.

Plot3D[Sin[x - Cos[y]], {x, -3, 3}, {y, -3, 3}]

Applying options to three-dimensional graphics works the same as with two-dimensional graphics; in fact, many of the options are the same.

One of the differences between two- and three-dimensional plotting in Mathematica is point sampling. Instead of adaptive sampling, three-dimensional plots rely on a fixed grid of points at which to evaluate the function. By default, a 15 × 15 grid is used, resulting in (15^2) = 225 points plotted; raising this number results in a smoother graph, but takes more time and memory to generate.

Here is a smoother graph of the same function as above.

Plot3D[Sin[x - Cos[y]], {x, -3, 3}, {y, -3, 3}, 
      Axes -> False, FaceGrids -> All, PlotPoints -> 25];

Changing the Viewpoint

One important option to three-dimensional plotting functions is the viewpoint, the point in space from which the observer looks at the object. ViewPoint is an option to all three-dimensional graphics functions. Its default value is {1.3, –2.4, 2.0}, which can be changed by entering a new value directly as an option.

Show[%, ViewPoint->{0,3,2}];

Mathematica provides an easier way to do this using the 3D ViewPoint Selector. To use this front-end feature we pull down the Input menu and choose 3D ViewPoint Selector. Rotating the box with the mouse will have Mathematica compute the point from which to view the object. The Paste button enters the viewpoint at the current text insertion point.

ParametricPlot3D

ParametricPlot3D is the three-dimensional analog of ParametricPlot. Depending on the input, ParametricPlot3D produces a space curve or a surface.

When we give ParametricPlot3D a list of three parametric functions in one parameter, the result is a space curve.

ParametricPlot3D[{Sin[t], Cos[t], t/3}, {t, 0, 6 π}, 
      Axes -> False];

A list of three parametric functions in two parameters results in a surface.

ParametricPlot3D[{Sin[v] Cos[u], Sin[v] Sin[u], Cos[v]}, {u, 0, 
        1.5 π}, {v, 0, π}];

Like most graphing functions, ParametricPlot3D accepts a list of sets of parametric equations and plots the surfaces together.

ParametricPlot3D[{{Sin[v] Cos[u], Sin[v] Sin[u], Cos[v]}, { 
          Sin[v] Cos[4 u/3]/2,  Sin[v] Sin[4 u/3]/2, Cos[v]/2}}, {u, 0, 
        1.5 π}, {v, 0, π}];

Options are given to ParametricPlot3D the same way as for Plot3D. Most of the options are the same.

Exercises: Three-Dimensional Graphics

Make a three-dimensional plot of the function sin(x+sin(y)) between -3 and 3 on both axes.

Plot3D[Sin[x + Sin[y]], {x, -3, 3}, {y, -3, 3}];

Enter Options[Plot3D] or use the on-line help to find a list of all the options that Plot3D accepts. Plot the same function again, this time changing at least four of Mathematica’s default options, including the options that control the smoothness of the plot and the color.

changedplot3d = 
      Plot3D[Sin[x + Sin[y]], {x, -3, 3}, {y, -3, 3}, 
        PlotPoints -> {15, 45}, Mesh -> False, 
        ColorFunction -> Hue, FaceGrids -> All];

Contour and Density Graphics

ContourPlot and DensityPlot

Mathematica plots contour and density plots of functions of two or three variables. These plotting functions work much like Plot and Plot3D with the exception of special options that apply only to contour and density plots.

ContourPlot displays a graphic of a function of two variables, where regions of different intensities of gray have (nearly) the same function value.

ContourPlot[Exp[x]Sin[y], {x, -3, 3}, {y, -3, 3}];

DensityPlot by default generates a grid of gray levels, where the lighter gray areas have greater function values than the darker gray areas.

DensityPlot[Exp[x] Sin[y], {x, -3, 3}, {y, -3, 3}];

ContourPlot3D

The function ContourPlot3D provides a way to plot surfaces showing particular values of a function of three variables. This function is defined in one of the standard add-on packages, so we must load the package before using the function.

Needs["Graphics`ContourPlot3D`"]

ContourPlot3D[fun, {x, (Subscript[x, 0]), (Subscript[x, 1])}, {y, (Subscript[y, 0]), (Subscript[y, 1])}, {z, (Subscript[z, 0]), (Subscript[z, 1])}] plots the surface implicitly defined by fun[x, y, z] == 0. Setting the option Contours to {(Subscript[val, 1]), (Subscript[val, 2]), … } plots the level surfaces corresponding to the values (Subscript[val, 1]), (Subscript[val, 2]), ….

ContourPlot3D[
      Sqrt[(x^2) + (y^2) + (z^2)], {x, -1, 1}, {y, 0, 1}, {z, 0, 1}, 
      Contours -> {0.25, 0.5, 0.75}];

Exercises: Contour and Density Graphics

Create a density plot of the function sin(x - sin(y)) over any range that includes the origin. Render the graphic with twice as many PlotPoints. Experiment with other options.

DensityPlot[Sin[x - Sin[y]], {x, -10, 10}, {y, -10, 10}];

DensityPlot[Sin[x - Sin[y]], {x, -10, 10}, {y, -10, 10}, 
      PlotPoints -> 30, Mesh -> False, FrameLabel -> {"x", "y"}];

Repeat the above exercise using ContourPlot instead of DensityPlot. Experiment with the options to ContourPlot that do not apply to DensityPlot.

ContourPlot[Sin[x - Sin[y]], {x, -10, 10}, {y, -10, 10}];

ContourPlot[Sin[x - Sin[y]], {x, -10, 10}, {y, -10, 10}, 
      PlotPoints -> 30, Contours -> 30, 
      ContourLines -> False];

Plotting Data

There are many occasions when we want to work with data rather than functions. There are several functions designed to visualize data in two or three dimensions. For these examples, we need data to work with. In practice, we would most likely read these data from a file or use the output of other calculations. For this demonstration we will create a list of ordered pairs to use as data.

exampleData = 
      N[Table[{n, n + Sin[n] + Random[]}, {n, 0, 5 π, 0.2 π}]];

ListPlot takes an array of data and plots it in two dimensions. Given a one-dimensional set of data such as {10, 20, 30, 40}, Mathematica plots the ordered pairs {{1, 10}, {2, 20}, {3, 30}, {4, 40}}. In this case we supply a list of ordered pairs and Mathematica plots the points using our explicit x values. (The graphics directive PointSize[p] specifies that points should be drawn so they are p percent of the width of the graph.)

pointplot = ListPlot[exampleData, PlotStyle -> PointSize[0.02]];

Options to ListPlot include nearly all of those applicable to Plot. One exception is the option PlotJoined, which when set to True draws a line connecting each of the points.

joinedplot = 
      ListPlot[exampleData, PlotJoined -> True, 
        PlotStyle -> RGBColor[0, 0, 1]];

At this point in our analysis we can easily find a good least-squares fit to these data. The function Fit takes as arguments a set of data, a set of basis functions for the best-fit polynomial, and a list of variables to be used. Here we include only constant, linear, and quadratic terms for the best-fit function.

exampleFit = Fit[exampleData, {1, x, (x^2)}, x]

Here is a plot of the best-fit quadratic polynomial.

fitplot = 
      Plot[exampleFit, {x, 0, 5 π}, PlotStyle -> Dashing[{0.01}]];

Here we combine the previous three graphs.

Show[{pointplot, joinedplot, fitplot}];

When working with three-dimensional data, we use analogs to Plot3D, DensityPlot, and ContourPlot. ListPlot3D plots a three-dimensional surface from a rectangular array of height values.

examplearray = 
      Table[n + Sin[n] + 3 Random[], {i, 1, 5 π, 0.3 π}, {n, 1, 
          5 π, 0.3 π}];

ListPlot3D[examplearray];

ListContourPlot and ListDensityPlot create density and contour plots from rectangular arrays of data.

ListDensityPlot[examplearray];

Exercises: Plotting Data

Create tabular data from the curve x cos(x) - sin((x^2)) between x = -2π and x = 2 π and display the data using ListPlot.

mydata = 
      Table[N[{x, x Cos[x] - Sin[(x^2)]}], {x, -2 π, 2 π, 
          0.05 π}];

ListPlot[mydata, PlotStyle -> PointSize[0.02]];

Create a list of the first 20 prime numbers. (Hint: use Table and Prime[n], which gives the (n^th) prime number.) Plot the list using ListPlot, then fit the data to a quadratic polynomial, and plot the data and the best-fitting curve on the same set of axes. Use options to change the color and other aspects of the graphic.

primes = Table[Prime[n], {n, 1, 20}]

pointplot = 
      ListPlot[primes, PlotStyle -> {Red, PointSize[0.02]}];

fitline = Fit[primes, {1, x, (x^2)}, x]

fitplot = Plot[fitline, {x, 0, 20}, PlotStyle -> {Blue}];

Show[{pointplot, fitplot}];

2. Using Packages

A number of tools that we use to create and customize Mathematica graphics are defined in the standard packages that ship with Mathematica. Generally, these packages either define new functions or graphics primitives. We may browse these packages using the help browser.

As an example, The Graphics`Arrow` package defines graphics primitives and options for drawing arrows. To load these functions into the Mathematica kernel, we execute the following Needs command.

?Arrow

Needs["Graphics`Arrow`"]

?Arrow

It is important to load the package defining a function before we first invoke that function, for if we don’t, we may shadow the package definition and prevent it from being correctly defined when we do load the package.

Each set of related packages also contains a master package that defines the names of all Mathematica symbols defined in those packages.  If we load this package first, using any function defined in any of the packages will cause that package to load automatically.

Needs["Graphics`Master`"]

If we use certain package functions often, it is a good idea to load them automatically by adding the appropriate lines to the init.m file.

init.m is a user-configurable package that is loaded last in the startup process. init.m can contain any code that we would like to be evaluated automatically each time we launch the Mathematica kernel. Here are some examples of code that might be found in an init.m file.

We could add a new directory to the search path contained in $Path.

AppendTo[$Path,\(\*""Hard Drive:"\)Mathematica:Mathematica Applications\(\*""]"\)

The following line changes the default viewpoint for three-dimesional graphics.

SetOptions[{Plot3D, ListPlot3D, Graphics3D, SurfaceGraphics},  
      ViewPoint -> {-2.581, -1.357, 1.717}];

Placing the following code in the init.m file will automatically load the Graphics`Colors` package each time the kernel is launched.

Needs["Graphics`Colors`"];

3. Selected Graphics Packages

Shapes

The standard package Graphics`Shapes` provides Mathematica definitions of common three-dimensional shapes.

Needs["Graphics`Shapes`"]

Once a package is loaded, we can get a list of all the objects that it defines by using ? with the full package name and * (to denote all objects).

?Graphics`Shapes`*

Torus[(Subscript[r, 1]), (Subscript[r, 2]), n, m] creates a list of n m polygons approximating a torus centered around the z axis with radii (Subscript[r, 1]) and (Subscript[r, 2]). Default values of (Subscript[r, 1]), (Subscript[r, 2]), n, and m are 1, 0.5, 20 (Subscript[r, 1]), and 20 (Subscript[r, 2]), respectively. The other shapes are defined similarly.

We use the Show command to render the object in our notebook.

Show[Graphics3D[Torus[1, 0.75, 25, 25]]];

Transformations on these Mathematica objects, such as WireFrame and RotateShape are wrapped around the shape, using the following syntax.

Show[WireFrame[Graphics3D[Torus[1, 0.75, 25, 25]]]];

Polyhedra

Graphics`Polyhedra` defines the polyhedra Tetrahedron, Cube, Hexahedron, Octahedron, Dodecahedron, SmallStellatedDodecahedron, GreatDodecahedron, GreatStellatedDodecahedron, Icosahedron, and GreatIcosahedron, as well as functions to operate on them: Faces, Geodesate, OpenTruncate, Stellate, Truncate, and Vertices.

Needs["Graphics`Polyhedra`"]

Polyhedron[name] gives a Graphics3D object representing the specified solid centered at the origin and with unit distance to the midpoints of the edges. The possible names are in the list Polyhedra.

Polyhedra

\(\(DisplayTogetherArray[{

        		{Show[Polyhedron[Tetrahedron], Boxed -> False], 
		
          Show[Polyhedron[Cube], Boxed -> False], 
		
          Show[Polyhedron[Octahedron], Boxed -> False], 
		
          Show[Polyhedron[Dodecahedron], Boxed -> False], 
		
          Show[Polyhedron[Icosahedron], Boxed -> False]}, 

        		{Show[Polyhedron[Hexahedron], Boxed -> False], 
		
          Show[Polyhedron[GreatDodecahedron], Boxed -> False], 
		
          Show[Polyhedron[SmallStellatedDodecahedron], Boxed -> False], 
          
		Show[Polyhedron[GreatStellatedDodecahedron], 
            Boxed -> False], 
		
          Show[Polyhedron[GreatIcosahedron], Boxed -> False]}}]; \)\)

Polyhedron[name, center, size] uses the given center and size.

\(\(Show[

      \ \ \ \ \ {\ Polyhedron[Dodecahedron, {4, 1, 0}, 2], 
		
        Polyhedron[Icosahedron, {4, 2, 5}, .5], 
		
        Stellate[Polyhedron[Icosahedron]]
\ }\ ]; \)\)

Alternatively, the polyhedra can be used as functions in their own right, each of which can take center and size options. This allows the easier  inclusion of other primitives and directives.

?Dodecahedron

\(\(DisplayTogetherArray[{
        Show[Graphics3D[Stellate[Dodecahedron[{0, 0, 0}, 10]]], 
          Axes -> True], 
		
        Show[Graphics3D[Stellate[Dodecahedron[{10, 10, 10}, 10]]], 
          Axes -> True]}]; \)\)

The package also includes functions for operating on polyhedra, such as Stellate, Geodesate, Truncate, and OpenTruncate.

\(\(DisplayTogetherArray[{
		
        Show[Stellate[Polyhedron[Icosahedron]], Boxed -> False], 
		
        Show[Geodesate[Polyhedron[Dodecahedron], 3], Boxed -> False], 

        		Show[Truncate[Polyhedron[Dodecahedron]], Boxed -> False], 

        		Show[OpenTruncate[Polyhedron[Dodecahedron]], 
          Boxed -> False]}]; \)\)

Notice in our examples that complex graphics objects are made up of several polygons.  EdgeForm allows us to specify directions for the drawing of the edges of these polygons. EdgeForm[ ] draws no lines at all on the edges of the polygons, while EdgeForm[g], where g is a list of graphics directives, draws polygon edges in the styles defined by g.

\(\(Show[\ 
      Graphics3D[

        \ \ \ \ \ \ \ \ \ \ \ \ \ \ {EdgeForm[], 

          \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ Dodecahedron[{2, 2, 2}, \ 1.2], 

          \ \ \ \ \ \ \ \ \ \ 	\ \ \ 
          EdgeForm[{GrayLevel[.4], \ Thickness[0.01]}], 

          \ \ \ \ \ \ \ \ \ \ 	\ \ \ 
          Stellate[Icosahedron[{0, 0, 0}, \ .5]]\ }

        \ \ \ \ \ \ \ \ 	\ \ \ ]]; \)\)

Lighting is an option to Show that can be True or False. In the default case,  Lighting is True, and we control the lighting of the surface just as we do for  three-dimensional plotting, by giving options such as LightSources to Show. Turning this option off allows us to control the shading of a surface via its intrinsic qualities. FaceForm[gfront, gback] allows the use of graphics directives for the front and back faces of  each polygon. To see the back face of a polygon, we first remove some of the pieces of an object. The internal form of Dodecahedron[ ] is a list of polygon specifications. We choose part of this list just as we would take part of a list of numbers.

partialdodec  =  Drop[ Dodecahedron[ ],  {4, 6} ];

\(\(Show[Graphics3D[{FaceForm[SlateGray, \ Maroon], partialdodec}\ ], \ 

      \ \ 	Lighting\  -> \ False, \ Boxed\  -> \ False]; \)\)

The Polyhedra package also provides functions for accessing the coordinates of the vertices and the vertex numbers of the faces for the various polyhedra.

Vertices[Dodecahedron] // First

Faces[Icosahedron] // First

Polyhedron[Octahedron] // First

Arrow

Arrow[start, finish] is a graphics primitive representing an arrow starting at start and ending at finish. Various options control the shape of the head of the arrow. We can control the proportions of the head of the arrow with HeadLength, HeadWidth, and HeadCenter, or we can specify an arbitrary graphic to use as the head of the arrow with HeadShape. HeadScaling controls the size of the head of the arrow, with default setting Automatic the head will be proportional to the length of the arrow. The setting Absolute will keep all arrowheads the same size.

Needs["Graphics`Arrow`"]

Show[Graphics[Arrow[{0, 0},  {1,  1}]]];

\(\(Show[
      Graphics[
{
          Table[{Hue[Random[]], Arrow[{0, 0}, \ t\ {Cos[t], \ Sin[t]}]}, 

            		{t, \ 0, \ 2  Pi, \ 0.25}]}\ ], \ 
      AspectRatio\  -> \ Automatic, PlotRange\  -> \ All]; \)\)

\(\(Show[
      Graphics[
{
          Table[Arrow[{t, 0}, \ {t, \ 1}, \ 
		HeadCenter\  -> \ t, 
              HeadLength\  -> \ .2], 
		{t, \ 0, \ 1, \ .2}]}], 
		
      AspectRatio\  -> \ Automatic, 
		
      PlotRange\  -> \ {{\(-.25\), \ 1.25}, \ All}]; \)\)

Since Arrow is a graphics primitive, it can be used with Epilog.

Plot[Sin[x], {x, 0, 2 π}, 
      Epilog -> {Arrow[{4, .5}, {π, 0}], 
          Text["(π,0)", {4.1, .6}]}];

Legend

The package Graphics`Legend` provides the ability to create a legend and place it in any two-dimensional graphic. There are two ways to use legends. First, as an option to Plot and, second, as a graphics object that can be combined with any two-dimensional graphics object.

Needs["Graphics`Legend`"]

Legends as a Plot Option

Specifying the option PlotLegend -> {(Subscript[text, 1]), (Subscript[text, 2]), … } in any plot command will produce a basic legend, with text for each curve plotted. If there are more curves than text, the text will be repeated cyclically.

\(\(Plot[{Sin[x]/x, 1/x}, {x, \(-10\), 10}, 
	
      PlotLegend\  -> \ {"Sin[x]/x", "1/x"}]; \)\)

The legend will incorporate styles assigned to the curves.

\(\(Plot[\ {Sin[x]/x, \ 1/x}, \ {x, \ \(-10\), 10}, 
		
      PlotStyle\  -> \ {GrayLevel[0.6], \ Dashing[{0.02}]}, 
		
      PlotLegend\  -> \ {Sin[x]/x, 1/x}]; \)\)

The form of each (Subscript[text, i]) can be altered by using StyleForm.

\(\(Plot[\ {Sin[x]/x, \ 1/x}, \ {x, \ \(-10\), \ 10}, 
	
      PlotStyle\  -> \ {GrayLevel[0.6], \ Dashing[{0.02}]}, 
	
      PlotLegend\  -> 

        		{StyleForm[Sin[x]/x, 
				FontFamily\  -> \ "Times", 

            				FontSlant -> "Italic", 
				FontSize -> 14], 

          		\ \ StyleForm[1/x, 
				FontFamily\  -> \ "Helvetica", 
            
				FontWeight\  -> \ "Bold", 
				
            FontSize\  -> \ 14]}]; \)\)

There are numerous options that affect the way the legend is drawn. As the examples show, Mathematica will do a good job creating, sizing, and placing legends on its own, but there are many aspects that may be controlled. LegendPosition, LegendSize, LegendShadow, LegendOrientation, LegendLabel, LegendTextDirection, LegendTextOffset, LegendSpacing, LegendTextSpace, LegendLabelSpace, LegendBorderSpace, LegendBorder, and LegendBackground allow us to determine the look and placement of the legend. Following is an example with many of these options changed.

\(\(Plot[\ {Sin[x]/x, \ 1/x}, \ {x, \ \(-10\), \ 10}, 
		
      PlotStyle\  -> \ {{RGBColor[1, 0, 0]}, \ {Dashing[{0.02}]}}, 
		
      PlotLegend\  -> \ 

        		\ \ \ {
          StyleForm[Sin[x]/x, 
				FontFamily\  -> \ "Times", 

            				FontSlant -> "Italic", FontSize\  -> \ 14], \ 
			
          StyleForm[1/x, 
				FontFamily\  -> \ "Helvetica", 

            				FontWeight\  -> \ "Bold", \ FontSize\  -> \ 12]}, 

      		LegendPosition\  -> \ {\(-1\), \ 0.15}, \ 
		
      LegendSize\  -> \ {0.75, 0.8}, 
		
      LegendShadow\  -> \ {0.075, \ 0.1}, \ 
		
      LegendLabel\  -> \ 
			
        StyleForm["Example", \ FontFamily\  -> \ "Times", 
			
          FontWeight\  -> \ "Bold", \ FontSize\  -> \ 18], 
		
      LegendBorder\  -> \ 
			{RGBColor[0.4, 1, 0.7], \ Thickness[0.02]}, 
      
		LegendBackground\  -> \ Yellow, 
		
      ShadowBackground\  -> \ SlateGray				\ \ \ 
	]; \)\)

Legends in Other Types of Graphics

The form ShowLegend[graphic, (Subscript[legend, 1]), (Subscript[legend, 2]), …] will place the legends specified in the graphic, where graphic is any graphic. Each (Subscript[legend, i]) has the form {{{(Subscript[box, 1]), (Subscript[text, 1])}, … }, opts} where each (Subscript[box, i]) is a color primitive or graphic and each (Subscript[text, i]) is an expression. A special form for a legend with n boxes, each colored according to the function colorfunction is {colorfunction, n, minstring, maxstring, opts}, where minstring and maxstring are optional text strings to be placed with the end boxes.

The next example uses this form. Since we know that ContourPlot shades each contour by mapping the function value onto GrayLevel, we can easily mimic this in the legend.

ShowLegend[ ContourPlot[ Sin[x y], {x, 0, Pi}, 
					{y, 0, Pi}, ContourLines -> False,
					Contours -> 35, 
					DisplayFunction -> Identity],
			
			{GrayLevel[1-#]&, 10, " 1", "-1",
			 LegendPosition -> {1.1, -.4}}];

\(\(ShowLegend[
	
      DensityPlot[Sin[x\^2 - Cos[y\^2]], {x, \(-3\), 3}, \ {y, \(-3\), 3}, 

        			Mesh -> False, PlotPoints -> 30, DisplayFunction -> Identity], 
      
{GrayLevel[1 - #]&, 10, " 1", "-1", 
			
        LegendPosition -> {1.1, \(-0.4\)}}]; \)\)

Needs["Graphics`Colors`"]

func[a_,b_,c_] := c/(b x)^(a Log[b x]);

ShowLegend[ 
 Plot[{func[2,2,1], func[2,4,1], func[4,4,1]}, {x, 0.001, 1},
	PlotStyle -> {Red, Green, Blue},
	PlotLabel -> StyleForm[c/(b x)^(a Log[b x]),
				 FontFamily -> "Helvetica", 
				 FontWeight -> "Bold", FontSize -> 12],
				 DisplayFunction -> Identity],
			
{{{Red, "2,2,1"}, {Green, "2,4,1"}, {Blue, "4,4,1"}},
LegendPosition -> {1, -.4}, LegendSize -> {1,1},
LegendLabel -> StyleForm["Values of a, b, c",
			   FontFamily -> "Helvetica", FontWeight -> "Bold",
			   FontSize -> 10]}];

A legend may be created as a standalone graphics object by using the function Legend[legendargs, opts], where legendargs is of the form {{(Subscript[box, 1]), (Subscript[text, 1])}, … }. We may also generate just the graphics primitives describing the legend’s box and drop shadow with the command ShadowBox[pos, size, opts]. Options for ShadowBox are ShadowOffset, ShadowBackground, ShadowForeground, and ShadowBorder. Note that these options can also be included in calls to ShowLegend, PlotLegend, or Legend.

Exercises: Selected Graphics Packages

Load the package Graphics`Master`. This loads the name of every function defined in a graphics package into memory, and tells Mathematica to load the appropriate package when a package function is first used.

Needs["Graphics`Master`"]

Have Mathematica draw the default Cylinder. Draw another cylinder whose length is twice its diameter and use twice the number of polygons as Mathematica would by default. Use RotateShape to rotate this Cylinder off the vertical. Use AffineShape to deform the cylinder in any interesting way.

?Cylinder

Show[Graphics3D[Cylinder[ ]], Boxed -> False];

Show[Graphics3D[Cylinder[1, 2, 40]], Boxed -> False];

?RotateShape

\(\(Show[
      Graphics3D[
		
        RotateShape[Cylinder[1, 2, 40], 0, π\/2, π\/2]], 
		
      Boxed -> False]; \)\)

?AffineShape

\(\(Show[
      Graphics3D[
		AffineShape[Cylinder[1, 2, 40], {0.2, 0.5, 0.02}]], 

      		Boxed -> False]; \)\)

Do the same with any other shape.

Create a two-dimensional plot with two or more functions and attach a legend to it.

\(\(Plot[{x, x\^2, x\^3}, \ {x, 0, 10}, 
	
      PlotStyle -> {GrayLevel[0.3], \ Dashing[{0.02}], \ Hue[0]}, 
	
      PlotLegend -> {x, x^2, x^3}]; \)\)

Modify the legend in the previous exercise using the various Legend options.

\(\(Plot[{x, x\^2, x\^3}, \ {x, 0, 10}, 
	
      PlotStyle -> {GrayLevel[0.3], \ Dashing[{0.02}], \ Hue[0]}, 
	
      PlotLegend -> {x, x^2, x^3}, 
	LegendPosition -> {1.1, \ \(-0.4\)}, 

      	LegendSize -> {0.9, \ 1}, 
	
      LegendLabel -> 
        StyleForm["Exponents", FontFamily -> "Times", 
          FontWeight -> "Bold", FontSize -> 18], 
	
      ShadowBackground -> GrayLevel[0.5]]; \)\)

4. Standard Add-on Packages

In addition to the graphics functions that are built into Mathematica, many of the functions defined in  the standard add-on packages increase Mathematica’s graphical capabilities. These functions allow us to create additional types of graphics, simplify some plotting tasks, or enhance functions already defined in the Mathematica kernel.

This section will provide an overview of all the graphics functions contained in the standard add-on packages. For more in-depth coverage of these functions, consult the Help Browser or the text Mathematica 3.0 Standard Add-on Packages, which is included with most versions of Mathematica 3.0.

Graphics

This group of packages contains most of the graphics functions found in the standard add-on packages. It is important to note that we could load each package indivdually as we needed to use the functions in that package, but there is a more convenient way to do this automatically. This is through the use of master packages.

Animation

This package contains various animation functions for regular x-y, density, contour, and parametric curve plots.  Animation of three-dimensional plots and rotation of two-dimensional plots is also supported.

Evaluate the following code to see examples of animation functions available in the Animation package.

Needs["Graphics`Animation`"]

Animate[
      Plot[Sin[x t], {x, -3, 3}, PlotRange -> {-1, 1}], {t, 0, 
        1}]

MoviePlot[Sin[x t], {x, -5, 5}, {t, 0, 1}, 
      PlotRange -> {-1, 1}

MoviePlot3D[Sin[x y t], {x, -2, 2}, {y, -2, 2}, {t, 0, 1}, 
      PlotRange -> {-1, 1}, Frames -> 24]

\(MovieParametricPlot[{Sin[x\ t], Cos[x\ t]}, {x, \(-π\), π}, {t, 
        0, 1, 1\/11}, 
	PlotRange -> {{\(-1\), 1}, {\(-1\), 1}}, 
      AspectRatio -> 1]\)

SpinShow[
      Plot3D[Sin[x y], {x, -2, 2}, {y, -2, 2}, Axes -> None, 
        Boxed -> False]];

ArgColors

This package provides functions for specifying the color or gray level of graphics elements using the argument of a complex number.

Needs["Graphics`ArgColors`"]

func[z_] := Exp[((2 π I z)/10)]

\(\(circ1\  = \ 
	
      Graphics[Table[

          			{ArgShade[func[z]], Disk[{Re[func[z]], Im[func[z]]}, 0.2]}, 

          	{z, 10}], AspectRatio -> Automatic]; \)\)

\(\(circ2\  = \ 
	
      Graphics[Table[

          			{ArgColor[func[z]], Disk[{Re[func[z]], Im[func[z]]}, 0.2]}, 

          	{z, 10}], AspectRatio -> Automatic]; \)\)

\(\(circ3\  = \ 
	
      Graphics[Table[

          			{ColorCircle[func[z]], 
            Disk[{Re[func[z]], Im[func[z]]}, 0.2]}, 
	{z, 10}], 
        AspectRatio -> Automatic]; \)\)

Show[GraphicsArray[ {circ1, circ2, circ3} ]];

Colors

This package provides functions that convert a color expressed in one of several color systems to an RGBColor. It also allows you to find the appropriate RGBColor for a particular color name (such as Blue).

Needs["Graphics`Colors`"]

The following example code will display a vertical listing of the name and a swatch of each color in the Colors package.

Use this definition for colors for ten random colors.

colors  =  
      Sort[Table[
          AllColors[[Random[Integer,  {1, Length[AllColors]}]]], {10}]];

Use this initial value for colors if you want an alphabetical listing of the all colors available.

colors  =  AllColors;

Use these two lines to create a listing of all colors available sorted by their CMYKColor value.

colors = ({#1, ToColor[ToExpression[#1], CMYKColor]}&)/@AllColors; 
    colors = First[
        Transpose[
          Sort[colors, 
            OrderedQ[{#1[[2]], #2
                    [[2]]}]&]]];

The rest of this code can be used by either value of colors above to display the color names and swatches.

\(colors = 
      Table[{ToExpression[colors[[i]]], 
          
			Rectangle[{0, \(-10\)\ i}, {15, \(-10\)\ i - 10}], 
          RGBColor[0, 0, 0], 
          Text[colors[[i]], {20, 
              \(-10\)\ i - 5}, {\(-1\), 0}]}, {i, Length[colors]}]; 

    Show[Graphics[colors], 
	AspectRatio -> Automatic, 
      PlotRange -> {{0, 80}, {0, \(-\((Length[colors]\ 10 + 10)\)\)}}]; 
    \)

ComplexMap

This package plots the images of Cartesian coordinate lines and polar coordinate lines under a user-supplied function f.

Needs["Graphics`ComplexMap`"]

\(\(DisplayTogetherArray[{
	
        CartesianMap[Cos, {0.2, π - 0.2}, {\(-2\), 2}], 
	
        CartesianMap[Zeta, {0.1, 0.9}, {0, 20}], 
	
        CartesianMap[
          1\/Conjugate[#1]&, {\(-2\), 2, 4\/19}, {\(-2\), 2, 4\/19}, 
		
          PlotRange -> All]}]; \)\)

\(\(DisplayTogetherArray[{
	
        PolarMap[Log, {0.1, 10, 0.5}, {\(-3\), 3, 0.15}], 
	
        PolarMap[
          1\/Conjugate[#1]&, {0.1, 5.1, 0.5}, {\(-π\), π, 
            π\/12}], 
	
        PolarMap[Sqrt, {1}, {\(-π\) - 0.0001, π}], 
	
        PolarMap[Identity, {1, 2}, {\(-π\), π, π\/12}, 
          Frame -> True]}]; \)\)

ContourPlot3D

This package introduces ContourPlot3D and ListContourPlot3D, the three-dimensional analogs of the built-in functions ContourPlot and ListContourPlot.

Needs["Graphics`ContourPlot3D`"]

\(\(DisplayTogetherArray[{
		
        ContourPlot3D[
          x\ y\ z, {x, \(-1\), 1}, {y, \(-1\), 1}, {z, \(-1\), 1}, 
			
          Contours -> {.1}], 
		
        ContourPlot3D[
          \@\(x\^2 + y\^2 + z\^2\), {x, \(-2\), 2}, {y, \(-2\), 2}, {z, 
            \(-2\), 2}, 
			Contours -> {1.}], 
		
        ContourPlot3D[
          Sin[\@\(x\^2 + y\^2 + z\^2\)], {x, \(-2\), 2}, {y, 0, 2}, {z, 
            \(-2\), 2}, 
			Contours -> {0.75}]}]; \)\)

\(data = 
      Table[x\^2 + 2\ y\^2 + 3\ z\^2, 

        		{z, \(-1\), 1, 0.25}, {y, \(-1\), 1, 0.25}, {x, \(-1\), 1, 
          0.25}]; 

    ListContourPlot3D[data, 
	
      MeshRange -> {{\(-1\), 1}, {\(-1\), 1}, {\(-1\), 1}}, 
      Contours -> {3.}]; \)

FilledPlot

This package allows us to fill the space between a plotted function and the x-axis or between a pair of plotted functions with a color.

Needs["Graphics`FilledPlot`"]

\(\(DisplayTogetherArray[{
		FilledPlot[Sin[x]\/x, {x, \(-10\), 10}], 
        FilledPlot[{Sin[x]\/x, Cos[x]\/x, 1\/x}, {x, \(-10\), 10}], 
        FilledPlot[{x\^2\/18, Cos[x], Sin[x]}, {x, 0, 2\ π}, 
          Fills -> {{{1, Axis}, GrayLevel[0.8]}, {{2, 3}, 
                GrayLevel[0.3]}}, Curves -> Front]}]; \)\)

FilledListPlot[{2, 3, 1, 5, 4}];

\(\(DisplayTogetherArray[{
		
        Show[Graphics[

            				{GrayLevel[0.6], Polygon[{{0, 0}, {1, 0}, {1, 1}}]}, 
            AxesFront -> False, Axes -> True, 
            AxesOrigin -> {0.5, 0.5}]], 
		
        Show[Graphics[

            				{GrayLevel[0.6], Polygon[{{0, 0}, {1, 0}, {1, 1}}]}, 
            AxesFront -> True, Axes -> True, 
            AxesOrigin -> {0.5, 0.5}]]}]; \)\)

Graphics

This package provides special functions for plotting in two dimensions.  Special formats include bar charts, pie charts, log plots, polar plots, and error bar plots.

Needs["Graphics`Graphics`"]

LinearScale[1, 2]

Short[  LogScale[1, 10], 10  ]

UnitScale[2, 10, 0.7]

PiScale[0, 10]

\(\(DisplayTogetherArray[{
	
        TextListPlot[
		{{1.5, 2.5}, {1.6, 2.6}, {1.7, 2.7}, {1.8, 2.8}}, 
          
			TextStyle -> {FontSize -> 6}], 
	
        TextListPlot[{{1.5, 2.5, 4}, {1.6, 2.6, 3}, {1.7, 2.7, 2}, {1.8, 2.8, 
              1}}, 
			TextStyle -> {FontSize -> 6}], 
	
        LabeledListPlot[{{1.5, 2.5, 1}, {1.6, 2.6, 2}, {1.7, 2.7, 3}, {1.8, 
              2.8, 4}}, 
			TextStyle -> {FontSize -> 6}]}]; \)\)

\(\(DisplayTogetherArray[{

        		{LogPlot[Sin[x], {x, 0.1, 3.1}], 
	\ \ \ \ \ 
          LogPlot[Exp[4\ x], {x, 1, 5}, Frame -> True]}, 

        	\ \ {LogPlot[Exp[2\ x], {x, 1, 5}, 
			Frame -> True, 
            GridLines -> {Automatic, LogGridMajor}], 
	\ \ \ \ 
          LogPlot[Exp[4\ x], {x, 1, 3}, 
			Frame -> True, 
            GridLines -> {Automatic, LogGridMinor}]}}]; \)\)

\(\(DisplayTogetherArray[{
		
        LogListPlot[Table[{i\/2, i\^2}, {i, 20}]], 
		
        LogLogPlot[Sin[x], {x, 0.1, 3.1}], 
		
        LogLogListPlot[Table[{i\^2, i\^3}, {i, 10}]]}]; \)\)

\(\(DisplayTogetherArray[{
		
        PolarPlot[{Cos[t], Sin[2\ t]}, {t, 0, 2\ π}], 
		
        PolarListPlot[Table[{t\/2, Cos[t]}, {t, 0, 2\ π, 0.1}]]}]; \)\)

\(\(DisplayTogetherArray[{
		ErrorListPlot[Table[{i, \@i}, {i, 10}]], 
        
		ErrorListPlot[Table[{Sin[t], Cos[t], t}, {t, 10}]]}]; \)\)

data = 
      Table[{(n/15), ((((n/15)))^2) + 2 + Random[Real, {-0.3, 0.3}]}, {n, 
          15}]; datafit = Fit[data, {1, x, (x^2)}, x]; ListAndCurvePlot[data, datafit, {x, 0, 1}];

\(\(DisplayTogetherArray[{
		BarChart[Table[i, {i, 1, 10}]], 
		
        BarChart[Table[{Sin[t], Sin[t]}, {t, 0.6`3, 3`3, 0.6`3}]]}]; \)\)

\(\(DisplayTogetherArray[{
		PieChart[Table[i, \ {i, \ 5}]], 
		
        PieChart[Table[{i, \ A[i]}, \ {i, \ 7}]]}]; \)\)

\(\(DisplayTogetherArray[{
		PieChart[{.2, .3, .1}], 
		
        PieChart[{.2, .3, .1}, PieExploded -> All], 
		
        PieChart[{.2, .3, .1}, PieExploded -> {3, .2}]}]; \)\)

PlotStyle[Plot[Sin[x], {x, 0, π}]]

PlotStyle[
      Plot[Sin[x], {x, 0, π}, 
        PlotStyle -> {{Dashing[{.02, .02}], Thickness[.007]}}]]

?TransformGraphics

\(g1 = 
      Plot[Sin[t], {t, 0, 2  π}, \ DisplayFunction -> Identity]; 

    g2 = TransformGraphics[g1, \((Sin[#] + Cos[#])\)&]; 

    Show[GraphicsArray[{g1, \ g2}]]; \)

\(g1 = Plot[Sin[t], {t, 0, π}, DisplayFunction -> Identity]; 

    g2 = SkewGraphics[g1, {{1, 2}, {0, 1}}]; 

    Show[GraphicsArray[{g1, \ g2}]]; \)

Graphics3D

This package provides special functions for plotting in three dimensions.  Special formats include bar charts, scatter plots, surface plots, shadow plots, and projections.

Needs["Graphics`Graphics3D`"]

Needs["Graphics`ParametricPlot3D`"]\(g1 = 
      CylindricalPlot3D[r\^2, {r, 0, 1}, {ϕ, 0, 2\ π}, 
		
        DisplayFunction -> Identity]; 

    g2 = TransformGraphics3D[g1, Cos[#1]&]; 

    Show[GraphicsArray[{g1, \ g2}]]; \)

Show[Graphics3D[Plot[Sin[t], {t, 0, π}]]];

\(\(DisplayTogetherArray[

      	{CylindricalPlot3D[r\^2, {r, 0, 1}, {ϕ, 0, 2\ π}, 
			\ 
          Axes -> False], 
		
        Show[SkewGraphics3D[g1, {{1, 2, 0}, {0, 1, 0}, {0, 0, 1}}], 
			
          Axes -> False]}]; \)\)

\(g1 = 
      Table[Plot[x\^n, {x, 0, 5}, TextStyle -> {FontSize -> 6}, 
          DisplayFunction -> Identity], {n, 4}]; 

    DisplayTogetherArray[{
		Show[GraphicsArray[Partition[g1, \ 2]]], 

        		Show[StackGraphics[g1]]}]; \)

BarChart3D[{{1, 2, 3}, {4, 5, 6}}];

\(\(DisplayTogetherArray[{
	
        ScatterPlot3D[Table[{t, Sin[t], Cos[t]}, {t, 0, 10, 0.1}], 
			
          Axes -> False], 
	
        ScatterPlot3D[Table[{t, Sin[t], Cos[t]}, {t, 0, 10, 0.1}], 
			
          PlotJoined -> True, \ Axes -> False]}]; \)\)

ListSurfacePlot3D[
      Table[{i, j, Sin[i - Cos[j]]}, {i, 1, 10, .5}, {j, 1, 10, .5}]];

\(g1 = 
      ParametricPlot3D[{x, Cos[t]\ Sin[x], Sin[t]\ Sin[x]}, 

        		{x, \(-π\), π}, {t, 0, 2\ π}, 
		
        Axes -> False, DisplayFunction -> Identity]; 
    g2 = Shadow[g1, ZShadow -> False, DisplayFunction -> Identity]; 
    g3 = Show[Project[g1, {0, 1, 0}], DisplayFunction -> Identity]; 
    Show[GraphicsArray[{g1, g2, g3}], 
      DisplayFunction -> $DisplayFunction]; \)

ImplicitPlot

The built-in function Plot requires one to specify an explicit function. Many simple graphs (e.g., circles, ellipses, etc.) are not functions. ImplicitPlot allows one to plot figures defined by equations.

Needs["Graphics`ImplicitPlot`"]

\(\(DisplayTogetherArray[{

        		{ImplicitPlot[x\^2 + y\^2 == x\ y + 3, {x, \(-3\), 3}], 
		
          ImplicitPlot[\((x\^2 + y\^2)\)\^2 == x\^2 - y\^2, {x, \(-2\), 2}], 
          
		ImplicitPlot[x\^3 + y\^3 == 3\ x\ y, {x, \(-3\), 3}], 
		
          ImplicitPlot[x\^2 + y\^2 == 3\ x\ y + 3, {x, \(-10\), 10}, 
            PlotRange -> {{\(-10\), 10}, {\(-10\), 10}}]}, 

        		{ImplicitPlot[{\((x\^2 + y\^2)\)\^2 == x\^2 - y\^2, 
              \((x\^2 + z\^2)\)\^2 == 2\ x\ z}, {x, \(-2\), 2}, 
			
            PlotStyle -> {GrayLevel[0], Dashing[{.01}]}], 
		
          ImplicitPlot[x\^2 + y\^2 == π, {x, \(-2\), 2}], 
		
          ImplicitPlot[
            Sin[2\ x] + Cos[3\ y] == 1, {x, \(-2\)\ π, 2\ π}, {y, 
              \(-2\)\ π, 2\ π}], 
		
          ImplicitPlot[
            x\^3 + x\ y + y\^2 == 1, {x, \(-2\)\ π, 2\ π}, {y, 
              \(-2\)\ π, 2\ π}]}}]; \)\)

MultipleListPlot

This package contains a function for plotting multiple sets of data in a graph and related utilities.

Needs["Graphics`MultipleListPlot`"]

\(list1 = Table[{x, Sin[x]}, {x, 0, 2  π, π\/6}]; 

    list2 = Table[{x, Cos[x]}, {x, 0, 2  π, π\/6}]; \)

MultipleListPlot[list1, list2, PlotJoined -> True, ];

\(\(MultipleListPlot[

      	{2, 
	{1.5, 3.2}, 
	{2.5, ErrorBar[0.3]}, 

        	{{4.4, 5.2}, ErrorBar[{\(-0.5\), 0.3}]}, 

        	{{5.5, 2.1}, ErrorBar[{\(-0.4\), 0.3}, {\(-0.2\), 0.5}]}}, 

      Frame -> True]; \)\)

\(\(Show[Graphics[RegularPolygon[10, 1, {0, 0}, 0, 3]], 
	
      AspectRatio -> Automatic]; \)\)

\(\(Show[
      Graphics[MapIndexed[

          			{#1, Line[{{0, \(-First[#2]\)}, {1, \(-First[#2]\)}}]}&, 

          		{Dashing[{Dot}], 
		\ \ Dashing[{Dot, Dash}], 
		\ \ 
            Dashing[{Dot, Dash, Dot, LongDash}], 
		\ \ 
            Dashing[{Dot, Dot, Dash}]}]]]; \)\)

ParametricPlot3D

This package allows us to specify the step size of the grid used by ParametricPlot3D.  In contrast, the built-in function ParametricPlot3D requires that the grid be specified using the option PlotPoints.  The package also introduces the functions PointParametricPlot3D, SphericalPlot3D, and CylindricalPlot3D.

Needs["Graphics`ParametricPlot3D`"]

\(\(DisplayTogetherArray[{

        		{ParametricPlot3D[{x, y, x\ y}, {x, \(-1\), 1, 0.2}, {y, \(-1\), 
              1}, Axes -> False], 
		
          ParametricPlot3D[{Cos[t], Sin[t], t\/6}, {t, 0, 4\ π, 
              π\/12}, Axes -> False], 
		
          CylindricalPlot3D[
            r\^2, {r, 0, 1}, {ϕ, \(-\(π\/4\)\), \(5\ π\)\/4}, 
            Axes -> False, ViewPoint -> {1.3, \(-2.4\), 1.6}]}, 

        		{SphericalPlot3D[
            Sin[θ]\^2, {θ, 0, π}, {ϕ, 0, 
              \(3\ π\)\/2}, Axes -> False], 
		
          CylindricalPlot3D[
            1.5\ \@\(1 + r\^2\), {r, 0, 2}, {ϕ, 0, 2\ π}, 
            Axes -> False], 
		
          ParametricPlot3D[{Cosh[z]\ Cos[ϕ], Cosh[z]\ Sin[ϕ], z}, {
              z, \(-2\), 2}, {ϕ, 0, 2\ π}, Axes -> False]}}]; 
    \)\)

PlotField

This package does plots of vector fields in the plane. PlotVectorField allows us to specify the functions describing the two components of the field.  PlotGradientField and PlotHamiltonianField plot the respective vector fields associated with a scalar function. PlotPolyaField plots the field associated with a complex-valued function.  ListPlotVectorField plots a rectangular array of vectors.

Needs["Graphics`PlotField`"]

\(\(DisplayTogetherArray[{
		
        PlotVectorField[{Sin[x\ y], Cos[x\ y]}, {x, 0, π}, {y, 0, 
            π}], 
		
        PlotGradientField[x\^3 + y\^4, {x, 0, 10}, {y, 0, 10}], 
		
        PlotPolyaField[\((x + I\ y)\)\^4, {x, 5, 10}, {y, 5, 10}]}]; \)\)

PlotField3D

This package does plots of vector fields in three dimensions. PlotVectorField3D allows us to specify the functions describing the three components of the field.  PlotGradientField3D plots the gradient vector field associated with a scalar function. ListPlotVectorField3D plots a three-dimensional array of vectors.

Needs["Graphics`PlotField3D`"]

\(\(DisplayTogetherArray[{
		
        PlotVectorField3D[{y, \(-x\), 0}\/z, {x, \(-1\), 1}, {y, \(-1\), 1}, {
            z, 1, 3}], 
		
        PlotGradientField3D[
          x\ y\ z, {x, \(-1\), 1}, {y, \(-1\), 1}, {z, \(-1\), 1}], 
		
        ListPlotVectorField3D[
			
          Flatten[Table[{{i, j, k}, 

                						{Random[Real, {\(-1\), 1}], 
                  Random[Real, {\(-1\), 1}], Random[Real, {\(-1\), 1}]}}, {i, 
                7}, {j, 7}, {k, 7}], 2]]}]; \)\)

Shapes

This package provides lists of polygons for some common three-dimensional shapes.  Functions for translating, rotating, and affine transformations of Graphics3D objects and converting a Graphics3D object to its wire frame representation are also included.

Needs["Graphics`Shapes`"]

\(\(DisplayTogetherArray[{

        		{Show[Graphics3D[Cylinder[0.5, 0.5]], Boxed -> False], 
		
          Show[Graphics3D[Torus[2, 0.7, 15, 14]], Boxed -> False], 
		
          Show[Graphics3D[Sphere[]], Boxed -> False], 
		
          Show[Graphics3D[MoebiusStrip[2, 1, 80]], Boxed -> False], 

          		Show[Graphics3D[Helix[]], Boxed -> False]}, 

        		{Show[Graphics3D[DoubleHelix[]], Boxed -> False], 
		
          Show[RotateShape[Graphics3D[MoebiusStrip[]], π\/4, π\/3, 
              π\/2], Boxed -> False], 
		
          Show[TranslateShape[
              RotateShape[Graphics3D[MoebiusStrip[]], π\/4, π\/3, 
                π\/2], {1, 2, 3}], 
					
            RotateShape[Graphics3D[MoebiusStrip[]], π\/4, π\/3, 
              π\/2], Boxed -> False], 
		
          Show[AffineShape[Graphics3D[Cone[]], {1, 2, 3}], 
            Boxed -> False], 
		
          Show[WireFrame[Graphics3D[Cone[]]], Boxed -> False]}}]; \)\)

Spline

This package introduces a Spline graphics primitive and provides utilities for rendering splines.

Needs["Graphics`Spline`"]

\(pts\  = \ {{0, 0}, {1, 2}, {\(-1\), 3}, {0, 1}, {3, 0}}; 

    DisplayTogetherArray[{
		
        Show[Graphics[{Hue[0], \ Line[pts], \ GrayLevel[0], \ 
              Spline[pts, \ Cubic]}], PlotRange\  -> All], 
		
        Show[Graphics[{Hue[0], \ Line[pts], \ GrayLevel[0], \ 
              Spline[pts, \ Bezier]}], PlotRange\  -> All], 
		
        Show[Graphics[
            Spline[pts, \ CompositeBezier, \ 
              SplineDots -> Automatic]]]}]; \)

SurfaceOfRevolution

This package provides functions for plotting surfaces generated by revolving a curve about an axis.  The curve may be expressed as a function, parametrically, or as a list of points.  Rotation can be about an arbitrary axis.

Needs["Graphics`SurfaceOfRevolution`"]

\(\(DisplayTogetherArray[{

        	{SurfaceOfRevolution[Sin[x], {x, 0, 2  π}], 
		
          SurfaceOfRevolution[{1.1\ Sin[u], u\^2}, {u, 0, \(3  π\)\/2}, 
            BoxRatios -> {1, 1, 2}]}, 

        	{SurfaceOfRevolution[x\^2, {x, 0, 1}, RevolutionAxis -> {1, 1, 1}], 
          
		ListSurfaceOfRevolution[
            Table[{n, n\^3}, {n, 0, 1, 0.1}], {t, 0, π\/2}, 
			
            RevolutionAxis -> {1, \(-1\), 1}, PlotRange -> All]}}]; \)\)

ThreeScript

This package provides a utility for converting three-dimensional graphical objects from Mathematica to the 3-Script file format and writing them into files (or suitable operating system pipes).

Needs["Graphics`ThreeScript`"]

obj = Graphics3D[Polygon[{{0, 0, 0}, {0, 1, 0}, {0, 1, 1}}]]

ThreeScript["object.ts", obj]

! ! object.ts

DiscreteMath

Combinatorica

This package defines over 230 combinatoric and graph theory functions. It includes functions for constructing graphs and other combinatorial objects, computing invariants of these objects, and finally displaying them.

The package contains all the programs from the book, Implementing Discrete Mathematics: Combinatorics and Graph Theory with Mathematica, by Steven S. Skiena, Addison-Wesley Publishing Co., Advanced Book Program, 350 Bridge Parkway, Redwood City CA 94065.  ISBN 0-201-50943-1. For ordering information, call 1-800-447-2226.

The programs from the book, Implementing Discrete Mathematics: Combinatorics and Graph Theory with Mathematica, are available by anonymous ftp.cs.sunysb.edu in the pub/Combinatorica directory.  

Any comments, bug reports, or requests to get on the Combinatorica mailing list should be forwarded to:

Steven Skiena
Department of Computer Science
State University of New York
Stony Brook, NY 11794

skiena@sbcs.sunysb.edu

(516) 632-9026 / 8470

Needs["DiscreteMath`Combinatorica`"]

c1 = FerrersDiagram[RandomPartition[100]];

c2 = ShowGraph[CompleteGraph[5]];

c3 = ShowGraph[RankedEmbedding[GridGraph[5, 5], {13}]];

c4 = ShowGraph[LineGraph[CompleteGraph[5]]];

c5 = ShowGraph[CirculantGraph[21, RandomKSubset[Range[10], 3]]];

c6 = ShowGraph[OrientGraph[Wheel[10]], Directed];

c7 = ShowLabeledGraph[MakeGraph[Range[8], (Mod[#1, #2] == 0)&]];

c8 = ShowGraph[MinimumSpanningTree[CompleteGraph[6, 6, 6]]];

Show[GraphicsArray[{{c1, c2, c3, c4}, {c5, c6, c7, c8}}]];

ComputationalGeometry

This package implements selected functions from computational geometry relevent to nearest neighbor point location, including triangulation.

Needs["DiscreteMath`ComputationalGeometry`"]

\(input2D
       = {{4.4, 14}, {6.7, 15.25}, {6.9, 12.8}, {2.1, 11.1}, 

        										{9.5, 14.9}, {13.2, 11.9}, {10.3, 12.3}, {6.8, 
          9.5}, 
										{3.3, 7.7}, {.6, 5.1}, {5.3, 2.4}, {
          8.45, 4.7}, 

        										{11.5, 9.6}, {13.8, 7.3}, {12.9, 3.1}, {11, 
          1.1}}; 
input3D = 
      Map[{#1[[1]], #1
              [[2]], 
            \@\(64 - 
                \((\((#1[[1]])\) - 8)
                    \)\^2 - 
                \((\((#1[[2]])\) - 8)
                    \)\^2\)}&, input2D]; \)

\(\(DisplayTogetherArray[{

        		{PlanarGraphPlot[input2D, ConvexHull[input2D]], 
			
          PlanarGraphPlot[input2D]}, 

        		{DiagramPlot[input2D], 
			TriangularSurfacePlot[input3D]}}]; 
    \)\)

Tree

This package introduces functions for creating, searching and displaying trees represented as nested lists.

Needs["DiscreteMath`Tree`"]

TreePlot[MakeTree[Range[15]]];

ExprPlot[f[g[a, b, c, d], g[x, y, h[x, y]], g[x, y]]];

Geometry

Polytopes

This package contains functions that give geometric characteristics of regular polygons and polyhedra.

Needs["Geometry`Polytopes`"]

?Geometry`Polytopes`*

Area[Octagon]

vert  =  Vertices[Octagon]

Show[Graphics[{PointSize[.03], Point/@vert}, AspectRatio -> 1]];

Volume[Tetrahedron]

vert  =  Vertices[Tetrahedron]

Show[
      Graphics3D[{PointSize[.03], Point/@vert}, AspectRatio -> 1]];

TriangularSurfacePlot[vert];

Miscellaneous

WorldPlot

This package allows us to plot maps as graphic objects, where positions are expressed in terms of latitude and longitude.  The standard map projections Albers, Equirectangular, LambertAzimuthal, LambertCylindrical, Mercator, Mollweide, and Sinusoidal are included in the package. In addition, WorldPlot also loads data describing the names and outlines of countries of the world.

Needs["Miscellaneous`WorldPlot`"]

w1 = WorldPlot[NorthAmerica];

w2 = WorldPlot[{World, RandomGrays}];

\(\(w3 = 
      WorldPlot[{World, RandomGrays}, 
	WorldRotation -> {90, 0, 0}, 
        WorldRange -> {{0, 90}, {\(-180\), 180}}, 
	
        WorldProjection -> LambertAzimuthal]; \)\)

w4 = WorldPlot[{Africa, RandomGrays}, WorldProjection -> Sinusoidal];

\(\(w5 = 
      WorldPlot[Africa, 
		WorldBackground -> GrayLevel[0.7], 
		
        WorldGrid -> None, 
		WorldFrame -> Thickness[0.012], 
		
        WorldProjection -> LambertCylindrical]; \)\)

\({capetown, cairo} = 
	
      ToMinutes[{{{\(-33\), \(-56\)}, {18, 22}}, {{30, 3}, {31, 15}}}]; 

    w6 = Show[{w5, 
			
          WorldGraphics[

            				{Dashing[{0.05, 0.03}], Thickness[0.015], 
              Line[{capetown, cairo}]}]}]; \)

Show[
      GraphicsArray[Partition[Map[Graphics, {w1, w2, w3, w4, w5, w6}], 3]]];

NumericalMath

Butcher

This package gives the order conditions that a Runge-Kutta method must satisfy to be of a particular order. It works for both implicit and explicit methods. The package also calculates and plots Butcher trees and implements the functions of trees defined in John Butcher’s book, The Numerical Analysis of Ordinary Differential Equations: Runge-Kutta and General Linear Methods. Butcher’s row and column simplifying conditions assist in the derivation of high-order methods. A more compact and efficient stage-independent tensor notation has also been implemented.

Needs["NumericalMath`Butcher`"]

\(\(\(ButcherPlot[#, 
	ButcherPlotLabel -> \((InputForm\ /@\ #)\)]&\)\ @
      \ Flatten[ButcherTrees[4]]; \)\)

Microscope

This package allows functions to be plotted on a microscopic scale to exhibit the granularity of machine arithmetic.  Alternatively the actual error (measured in ulps (unit in the last place, i.e., one digit in the last place)) can be plotted.

Needs["NumericalMath`Microscope`"]

Microscope[Sqrt[x], {x, 5, 20}, PlotJoined -> Real];

MicroscopicError[Sqrt[x], {x, 5, 20}, PlotJoined -> Real];

OrderStar

This package plots the order star of an approximating function, to an essentially analytic function.  It is common to consider rational approximants to functions such as Padé approximants. Various information about a numerical scheme (such as order and stability) may be ascertained from its order star. For example, Runge-Kutta methods may be considered as rational approximants to the exponential, where relative and absolute stability regions are considered in terms of the linear scalar test problem of Dahlquist. The zeros, poles, and interpolation points convey important additional information and may also be displayed.

Needs["NumericalMath`OrderStar`"]

\(\(DisplayTogetherArray[{

        		{OrderStar[Pade[Exp[z], {z, 0, 1, 0}], E\^z], 
			
          OrderStar[Pade[Exp[z], {z, 0, 1, 0}], 1], 
			
          OrderStar[Pade[Exp[Cos[z] + I\ Cosh[z]], {z, 0, 2, 3}], 
				
            Exp[Cos[z] + I\ Cosh[z]], 
				
            PlotRange -> {{\(-5\), 5}, {\(-5\), 5}}, PlotPoints -> 40]}, 

        		{OrderStar[Pade[Log[1 + z], {z, 1, 3, 2}], Log[1 + z], 
				
            OrderStarKind -> Second, 
				PlotPoints -> 50, 
            PlotRange -> {{\(-0.5\), 2}, {\(-1\), 1}}, 
				
            OrderStarSubPlots -> 

              					{{PlotRange -> {{0.9, 1.1}, {\(-0.1\), 0.1}}, 
                  PlotPoints -> {20, 20}}}], 
			
          OrderStar[Pade[Exp[z], {z, 0, 2, 3}], Exp[z], 
				
            OrderStarPoles -> {True, False}, 
				
            OrderStarZeros -> {True, False}], 
			
          OrderStar[Pade[Sinh[z - 1], {z, 0, 3, 3}], Sinh[z - 1], 
					
            OrderStarLegend -> {{0.6, 0.6}, {0.98, 0.98}}, 
					
            TextStyle -> {FontFamily -> "Times", FontSize -> 4}, 

            					OrderStarSymbolSize -> 0.02]}}]; \)\)

Statistics

LinearRegression

This package provides least squares or weighted least squares linear regression for data whose errors are assumed to be normally and independently distributed.  It supports a number of commonly used statistics such as RSquared, EstimatedVariance, and an ANOVATable.  It also provides diagnostics for leverage, influence, collinearity, and correlation.

Needs["Statistics`LinearRegression`"]

This example demonstrates how to generate a ParameterConfidenceRegion of some data.

\(\(data
       = {{0.055, 90}, {0.091, 97}, {0.138, 107}, 

        						\ \ {0.167, 124}, {0.182, 142}, {0.211, 150}, 

        						\ \ {0.232, 172}, {0.248, 189}, {0.284, 209}, 

        						\ \ {0.351, 253}}; \)\)

\(regressdata = 
      Regress[data, {1, x\^2}, x, 
		
        RegressionReport -> ParameterConfidenceRegion]\)

\(\(Show[Graphics[ParameterConfidenceRegion /. regressdata], 
	
      Axes -> True, AxesLabel -> {"Constant", \*""\!\(x\^2\)""}]; 
    \)\)

MultiDescriptiveStatistics

This package computes descriptive statistics (location, dispersion, shape, and association statistics) for a sample represented as a data matrix. The data matrix is a list of independent identically distributed vector-valued or multivariate observations.

Needs["Statistics`MultiDescriptiveStatistics`"]

MultiDescriptiveStatistics defines two new graphics functions, Ellipsoid and Polytope. These functions are used in other statistics functions, including EllipsoidQuartiles and PolytopeQuartiles.

data = 
      N[{{1232, 4175}, {1115, 6652}, {2205, 7612}, {1897, 10914}, {1932, 
            10850}, {1612, 7627}, {1598, 6954}, {1804, 8365}, {1752, 9469}, {
            2067, 6410}, {2365, 10327}, {1646, 7320}, {1579, 8196}, {1880, 
            9709}, {1773, 10370}, {1712, 7749}, {1932, 6818}, {1820, 9307}, {
            1900, 6457}, {2426, 10102}, {1558, 7414}, {1470, 7556}, {1858, 
            7833}, {1587, 8309}, {2208, 9559}, {1487, 6255}, {2206, 10723}, {
            2332, 5430}, {2540, 12090}, {2322, 10072}}];

\({stiffness, strength} = Transpose[data]; 
    
{{minx, maxx}, {miny, maxy}} = 
      Map[{Min[#1], Max[#1]}&, {stiffness, strength}]; \)

\(q1 = 
      Graphics[EllipsoidQuartiles[data], 
		Frame -> True, 
        AspectRatio -> 1, 
		
        PlotRange -> {{minx, maxx}, {miny, maxy}}, 
        FrameTicks -> {{1200, 1600, 2000, 2400}, Automatic}]; 

    q2 = Graphics[PolytopeQuartiles[data], 
		Frame -> True, 
        AspectRatio -> 1, 
		
        PlotRange -> {{minx, maxx}, {miny, maxy}}, 
        FrameTicks -> {{1200, 1600, 2000, 2400}, Automatic}]; 

    Show[GraphicsArray[{q1, q2}]]; \)

Utilities

DXF

This package allows the export of Graphics3D objects to a file in the AutoCAD DXF format.

Needs["Utilities`DXF`"]

gr = 
      Plot3D[BesselJ[0, (Sqrt[(x^2) + (y^2)])], {x, -6, 6}, {y, -6, 6}, 
        PlotPoints -> 20];

gr = Graphics3D[gr];

WriteDXF["bessel.dxf", gr]

Some of the graphics primitives that can be transferred are Cuboid, Polygon, Line, and Point.

5. Colors

Built-in Color Functions

Colors can be specified in any of several color systems. RGBColor[r, g, b], where 0 ≤ r, g, b ≤ 1 specifies a color with the specified proportions of red, green, and blue. GrayLevel[level], where 0 ≤ level ≤ 1, specifies a shade of gray. CMYKColor[cyan, magenta, yellow, black] accepts arguments that are each between zero specifies colors in the CMYK color system. Hue[hue, saturation, brightness] allows color specification by hue, saturation and brightness levels, all of which must be between 0 and 1. The simplified form Hue[hue], which corresponds to Hue[h, 1, 1], allows color specification with one argument. As h varies from 0 to 1, Hue[hue] runs through red, yellow, green, cyan, blue, magenta, and back to red again. Values of h outside this range are taken mod 1.

Show[ Graphics[ 
{PointSize[.15], 
	RGBColor[0,0,1],Point[{0,0}], 
	CMYKColor[.2,.9,.6,.3], Point[{1,0}], 
	GrayLevel[.7], Point[{2,0}],
	Hue[.5], Point[{3,0}],
	Hue[.5, .4, .6], Point[{4,0}]}],
	PlotRange -> {{-1,5},Automatic}];

A color wheel can be created by mapping Hue over the sectors of a disk.

ColorWheel[n_] := 
      Show[Graphics[
          Map[{Hue[#/(2  π - n)], Disk[{0, 0}, 1, {#, # + n}]}&, 
            Range[0, 2  π - n, n]],  AspectRatio -> Automatic]]

wheel  =  ColorWheel[π/128];

Another way of specifying colors in Mathematica is by using the Color Selector built into the Mathematica front end. The menu item can be found, on the Macintosh, in the Input menu. Manipulate the controls until the shade you want appears in the New box. Clicking the OK button pastes the correct RGBColor specification at the current insertion point in the current notebook.

External Packages

Loading the package Graphics`Colors` provides definitions for three alternate color designation functions and 194 English names for colors and shades of gray. Once loaded, we can use these color names in place of the function calls defined earlier. AllColors is a list of all the defined colors.

Needs["Graphics`Colors`"]

Length[AllColors]

Short[AllColors, 10]

Here is the RGBColor value of the color VanDykeBrown.

VanDykeBrown

CMYColor[c, m, y] represents a color in the CMY (cyan-magenta-yellow) system, HLSColor[h, l, s] represents a color in the HLS  (hue-lightness-saturation) system, and YIQColor[y, i, q] represents a color in the YIQ (NTSC video form) system. These functions simply return the matching RGBColor specification.

\(\(Show[\ 
      Graphics[

        		{PointSize[0.15], 
			HLSColor[0.5, 0.7, 0.23], 
          Point[{0, 0}], 
			CMYColor[0.2, 0.3, 0.6], Point[{1, 0}], 

          			YIQColor[0.5, \(-0.1\), \(-0.05\)], Point[{2, 0}]}], 
			
      PlotRange -> {{\(-1\), 3}, Automatic}]; \)\)

The package Graphics`ArgColors` defines three more color utilities; ArgColor, ArgShade, and  ColorCircle. ArgColor[z] gives a color value whose hue is proportional to the argument of the complex number z, ArgShade[z] gives a gray level proportional to the argument of the complex number z, and ColorCircle[r, (light:1)] gives a color value whose hue is proportional to r (mod 2 π) with lightness light.

Needs["Graphics`ArgColors`"]

ArgColor[4  +  12  I]

Remember the definition of the color wheel from above. ColorCircle performs the same tranformation and allows a simpler definition.

ColorWheel[n_] := 
      Show[Graphics[
          ({Hue[#(1/(2 π - n))], Disk[{0, 0}, 1, {#1, #1 + n}]}&)/@
            Range[0, 2 π - n, n], AspectRatio -> Automatic]]

ColorWheel2[n_] := 
      Show[Graphics[
          ({ColorCircle[#1], Disk[{0, 0}, 1, {#1, #1 + n}]}&)/@
            Range[0, 2 π - n, n], AspectRatio -> Automatic]]

wheel2  =  ColorWheel2[π/128];

6. Graphics Primitives and Directives

Overview

All Mathematica graphics are built from a small number of graphics primitives and directives. The user may build arbitrary graphics in two and three dimensions from these basic building blocks of points, lines, circles, and so on. Graphics primitives define shapes, while graphics directives control the way the shape is drawn.

The following syntaxes are used to render a series of two- and thee-dimensional graphics, respectively.

Show[ Graphics[ { series of graphics primitives and directives } ] ]

Show[ Graphics3D[ { series of graphics primitives and directives } ] ]

Two-Dimensional Graphics Primitives

The primitives Point, Line, Rectangle, Polygon, Circle, Disk, Raster, RasterArray, and Text form the basis for all two-dimensional graphics.

Circle[ {x, y}, r ] is a two-dimensional graphics primitive that represents a circle of radius r centered at the point {x, y}. Circle[ {x, y}, {rx, ry}] yields an ellipse with semi-axes rx and ry. Circle[ {x, y}, r, {theta1, theta2}] represents a circular arc. Line[ {pt1, pt2, …} ] is a graphics primitive that represents a line joining a sequence of points. Text[expr, coords] is a graphics primitive that represents text corresponding to the printed form of expr, centered at the point specified by coords. Other primitives behave similarly.

\(\(Show[
      Graphics[{
			
          Polygon[{{0, 0}, {1, 1}, {0, 2}, {\(-1\), 1}, {0, 0}}], 
			
          Line[{{0, 0}, {1, 1}, {0, 2}, {\(-1\), 1}, {0, 0}}], 
			
          Line[{{0, 0}, {0, 2}}], 
			Circle[{0, 0}, 1], 
          Circle[{0, 0}, \@2], 
			Line[{{\(-2\), \(-2\)}, {2, 2}}], 
          Line[{{\(-2\), 2}, {2, \(-2\)}}], 
			
          Line[{{\(-2\), 0}, {2, 4}}], Line[{{\(-2\), 4}, {2, 0}}], 
			
          Line[{{0, 0}, {1, 0}, {1, 1}, {0, 1}, {0, 0}}], 
			
          Text["Duplicating", {\(-1\), \ 1.85}], 
			
          Text["the Square", {\(-1\), 1.7}]}], 
	Axes -> True, 
      AxesOrigin -> {0, 0}, AspectRatio -> Automatic, 
      PlotRange -> {Automatic, {\(-0.2\), 2.2}}]; \)\)

Raster and RasterArray provide a mechanism for representing a rectangular array of gray or colored cells, respectively.

rasterarrayexample = 
      Table[Hue[0.1 Mod[i, j]], {i, 2, 10}, {j, 2, 10}];

Show[Graphics[RasterArray[rasterarrayexample]]];

Graphics Directives

The directives Thickness, PointSize, and Dashing, and any valid color specification are the basic means of changing the way the graphics primitives are drawn. Interspersing these with the graphics primitives allows us to create any configuration necessary.

Thickness[ r ] is a graphics directive that specifies that lines that follow are to be drawn with a thickness r, where r is given as a fraction of the total width of the graph. Dashing[ {(Subscript[r, 1]), (Subscript[r, 2]), …} ] is a two-dimensional graphics directive which specifies that lines which follow are to be drawn dashed, with successive segments of lengths (Subscript[r, 1]), (Subscript[r, 2]), … (repeated cyclically). The (Subscript[r, i]) are given as a fraction of the total width of the graph. For each directive that scales sizes relative to the size of the graphic, there is a corresponding directive, for example, AbsoluteThickness, allowing us to exactly specify the size or thickness in printer’s points, approximately equal to (1/72)  inch.

\(\(Show[
      Graphics[{

          			{GrayLevel[0.5], 
				
            Polygon[{{0, 0}, {1, 1}, {0, 2}, {\(-1\), 1}, {0, 0}}]}, 

          			{Hue[0], Thickness[0.01], 
				
            Line[{{0, 0}, {1, 1}, {0, 2}, {\(-1\), 1}, {0, 0}}]}, 
				
          Line[{{0, 0}, {0, 2}}], 

          			{Dashing[{0.01}], 
				Circle[{0, 0}, 1], 
            Circle[{0, 0}, \@2], 
				Line[{{\(-2\), \(-2\)}, {2, 2}}], 
            Line[{{\(-2\), 2}, {2, \(-2\)}}], 
				
            Line[{{\(-2\), 0}, {2, 4}}], Line[{{\(-2\), 4}, {2, 0}}]}, 

          			{Thickness[0.01], 
				
            Line[{{0, 0}, {1, 0}, {1, 1}, {0, 1}, {0, 0}}]}, 

          			{Hue[0.65], 
				
            Text["Duplicating", {\(-1\), \ 1.85}], 
				
            Text["the Square", {\(-1\), 1.7}]}}], 
	Axes -> True, 
      AxesOrigin -> {0, 0}, AspectRatio -> Automatic, 
      PlotRange -> {Automatic, {\(-0.2\), 2.2}}]; \)\)

Additional Primitives for Three Dimensions

When creating three-dimensional graphics most of the same primitives apply providing we specify points in the appropriate way. Cuboid[{xmin, ymin, zmin}] is a three-dimensional graphics primitive that represents a unit cuboid, oriented parallel to the axes. Cuboid[{xmin, ymin, zmin}, {xmax, ymax, zmax}] specifies a cuboid by giving the coordinates of opposite corners.

\(\(Show[
      Graphics3D[{
			Cuboid[{0, 0, 0}], Cuboid[{5, 0, 0}], 
          Cuboid[{0, 5, 0}], Cuboid[{0, 0, 5}], Cuboid[{5, 0, 5}], 
          Cuboid[{5, 5, 0}], Cuboid[{0, 5, 5}], Cuboid[{5, 5, 5}], 
          Line[{{0.5, 0.5, .5}, {5.5, 5.5, 5.5}}], 
          Line[{{5.5, 0.5, .5}, {.5, 5.5, 5.5}}], 
          Line[{{0.5, 0.5, 5.5}, {5.5, 5.5, 0.5}}], 
          Line[{{5.5, 0.5, 5.5}, {.5, 5.5, 0.5}}], 
          Polygon[{{1, 1, 0}, {5, 1, 0}, {5, 5, 0}, {1, 5, 0}, {1, 1, 0}}], {
            PointSize[0.05], Point[{3, 3, 3}]}}], 
Boxed -> False]; \)\)

Additional Directives for Three Dimensions

SurfaceColor[col] is a three-dimensional graphics directive specifying that the polygons that follow should act as diffuse reflectors of light with a color given by col.

\(\(Show[
      Graphics3D[
		
        Table[{SurfaceColor[Hue[Random[]]], 
			
            Cuboid[
				{Random[Integer, {1, 15}], 
					
                Random[Integer, {1, 15}], 
					
                Random[Integer, {1, 15}]}]}, 
		{50}]]]; \)\)

EdgeForm[g] is a three-dimensional graphics directive that specifies that edges of polygons are to be drawn using the graphics directive or list of graphics directives g.

\(\(Show[
	
      Graphics3D[{
			EdgeForm[Thickness[0.02]], 
          Polygon[{{0, 0, 0}, {0, 1, 1}, {1, 1, 1}}], 
          EdgeForm[{Thickness[0.01], Hue[0]}], 
          Polygon[{{0, 0, 0}, {1, 1, 0}, {1, 1, 1}}]}]]; \)\)

FaceForm[gf, gb] is a three-dimensional graphics directive that specifies that the front faces of all polygons are to be drawn with the graphics primitive gf, and the back faces with gb.

\(\(view1\  = \ 
      Graphics3D[{
			FaceForm[Hue[0], RGBColor[0, 1, 0]], 
			
          Polygon[{{0, 0, 0}, \ {0, 1, 1}, \ {1, 0, 1}}]}, 
			
        Lighting -> False, 
			Axes\  -> \ True, \ Ticks\  -> \ None, \ 

        			AxesLabel\  -> \ {"x", \ "y", \ "z"}, 
			
        ViewPoint -> {1.300, \ \(-2.400\), \ 2.000}, ]; \)\)

\(\(view2\  = \ 
      Graphics3D[{
			FaceForm[Hue[0], RGBColor[0, 1, 0]], 
			
          Polygon[{{0, 0, 0}, \ {0, 1, 1}, \ {1, 0, 1}}]}, 
			
        Lighting -> False, 
			Axes\  -> \ True, \ Ticks\  -> \ None, \ 

        			AxesLabel\  -> \ {"x", \ "y", \ "z"}, 
			
        ViewPoint -> {1.300, \ 2.400, \ 2.000}]; \)\)

Show[GraphicsArray[{view1,  view2}]];

More about Text

The form Text[expr, coords] will produce text corresponding to the printed form of expr, centered at the point specified by coords, but there are several more options available. Third and fourth arguments to Text control the orientation alignment and orientation of the text with the form Text[expr, coords, align, orient]. Align is of the form {a, b} where a controls the left-right alignment and b controls the above-below alignment. orient is of the form {a, b} where a controls the rightside-up and upside-down alignment and b controls the horizontal-vertical alignment. Note that rotated text does not display correctly but does print correctly.

({{offset, Relation to
	coords, orient, Orientation of text}, {{0, 0}, Centered, {1, 0}, Horizontal (rightside–up)}, {{-1, 0}, Left Justified, {0, 1}, Vertical (up)}, {{1, 0}, Right Justified, {0, -1}, Vertical (down)}, {{0, -1}, Centered Above, {-1, 0}, Horizontal (upside–down)}, {{0, 1}, Centered Below, , }})

\(\(Show[
      Graphics[
		
        Table[Text["Text", \ {i, j}, 

            				{Random[Integer, {\(-1\), 1}], 
              Random[Integer, {\(-1\), 1}]}, 

            				{Random[Integer, {\(-1\), 1}], 
              Random[Integer, {\(-1\), 1}]}], 
		{i, 1, 5}, {j, 1, 5}]], 
      PlotRange -> {{0, 7}, {\(-1\), 7}}]; \)\)

TextStyle is an option for graphics functions and for Text that specifies the default style and font options with which text should be rendered. Options such as FontSize, FontSlant, FontFamily, FontColor, and Background are recognized.

Show[
      Graphics[Text["Hello World", {10, 10}, 
          TextStyle 
            -> {FontFamily -> "Times", 
              FontWeight -> "Bold", FontSize -> 20, 
              FontColor -> Hue[0.9], FontSlant -> "Italic", 
              Background -> Hue[0.4]}]]];

The same effect can be achieved using StyleForm. StyleForm[expr, options] prints using the specified style options. StyleForm[expr, "style"] prints using the specified cell style in the current notebook.

Table[
      StyleForm["text", FontFamily -> "Times", 
        FontSize -> s], {s, 10, 20}]

\(StyleForm[\ "Hello World", 	"Title"]\)

Among the aspects of Mathematica we will not discuss in this course is its typesetting capabilities. Display allows us to take typeset expressions and display them as graphics. stdout directs the output to the front end.

Display[$Output, ToBoxes[Nest[1 + 1/#&, x, 7]], "MPS"];

Exercises: Graphics Primitives and Directives

Below is the Mathematica code to draw a face. Use other two-dimensional graphics commands (e.g., Polygon) to add other features (nose, beard, hat, etc.) and make changes to the face (e.g., eye color). Experiment and have fun.

Show[
      Graphics[{Thickness[0.03], Circle[{0, 0}, 1], PointSize[0.04], 
          Point[{-.5, .3}], Point[{.5, .3}], 
          Circle[{0, -0.1}, .5, {π + (π/4), 
              2 π - (π/4)}]}], AspectRatio -> Automatic];

Show[
      Graphics[{Thickness[0.03], Circle[{0, 0}, 1], Thickness[0.009], Red, 
          Circle[{-0.5, 0.3}, 0.04], Circle[{0.5, 0.3}, 0.04], Blue, 
          Circle[{0, -0.1}, 
            0.5, {π + (π/4), 2 π - (π/4)}], Pink, 
          Polygon[{{-0.25, -0.9}, {0.25, -0.9}, {0, -1.25}}], 
          Green, Polygon[{{-0.6, 0.9}, {0.6, 0.9}, {0.6, 1.1}, {-0.6, 
                1.1}}], 
          Polygon[{{-0.4, 1.1}, {0.4, 1.1}, {.4, 1.5}, {-0.4, 
                1.5}}]}], AspectRatio -> Automatic];

7. Displaying and Combining Graphics

Show

Perhaps the most versatile tool Mathematica provides for working with graphics is the Show command. Show, in its simplest form, allows us to rerender a graphic that has already been generated. Show also allows us to change some of the options associated with a graphic while redrawing the graphic. In general, we can change those options that don’t affect the curve itself, such as the PlotRange.

firstplot  =  Plot[x Sin[x]^2,  {x,  0,  3  π}];

Show[firstplot,  
      PlotRange  ->  {{-5,  15}, {-5,  10}}];

Show will render two or more graphics together on the same set of axes, scaling them appropriately.

\(\(secondplot\  = \ 
      Plot[x\ Cos[x]\^2, \ {x, \ 0, \ 3\ π}, 
		
        PlotStyle\  -> \ {Dashing[{0.03}], \ Thickness[0.01]}]; \)\)

Show[firstplot, secondplot];

Show works the same with three-dimensional graphics as it does with two-dimensional plots.

first3d = 
      Plot3D[(1 - Sin[x]) (2 - Cos[2 y]), {x, -2, 2}, {y, 
          -2, 2}];

second3d = 
      Plot3D[(2 + Sin[x]) (1 + Cos[2 y]), {x, -2, 2}, {y, 
          -2, 2}];

Show[first3d,  second3d];

Sometimes when generating three-dimensional graphics with Show, it may be easier to visualize the different plots by giving each plot a separate color instead of the the default shading scheme.

\(\(Show[
	
      Plot3D[{\((1\  - \ Sin[x])\)\ \((2\  - \ Cos[2\ y])\), GrayLevel[0.4]}, 
        
		{x, \ \(-2\), \ 2}, \ {y, \ \(-2\), \ 2}, \ 
        DisplayFunction\  -> \ Identity], 
	
      Plot3D[{\((2\  + \ Sin[x])\)\ \((1\  + \ Cos[2\ y])\), \ 
          GrayLevel[0.8]}, \ {x, \ \(-2\), \ 2}, \ {y, \ \(-2\), \ 2}, \ 
        DisplayFunction\  -> \ Identity], 
	
      DisplayFunction\  -> \ $DisplayFunction]; \)\)

GraphicsArray

Another useful function is GraphicsArray, which allows us to create tables of graphics. It is important to know the difference between those functions that create graphics objects, those that render them, and those that do both. For example, Plot will both create and render a graphics object, Show will render a previously computed graphics object, and GraphicsArray will create a new graphics object from other graphics objects.

Show[GraphicsArray[{firstplot, secondplot}]];

Using GraphicsArray, we are able to create a two-dimensional array of any shape and fill it with Mathematica graphics.

\(\(Show[
      GraphicsArray[{{firstplot, secondplot}, 

          			{secondplot, firstplot, secondplot}}]]; \)\)

Rectangle

You have seen how to constuct regular arrays of graphics using GraphicsArray, but you can also combine and superimpose plots in any way with the Rectangle function.

Rectangle allows you to render a graphics object within a specified rectangle and then to display that rectangle with other rectangles or individually in another plot.

First we generate a graphics object.

\(\(rectplot\  = \ 
	
      Plot3D[Sin[x]\ Exp[y], \ {x, \ \(-5\), \ 5}, \ {y, \ \(-2\), \ 2}, 

        		Axes\  -> \ False]; \)\)

Now we can use Rectangle and the Show command to place two copies of a graphic wherever we wish.

\(\(Show[
      Graphics[{
			Rectangle[{0, 0}, \ {1, 1}, \ rectplot], 
			
          Rectangle[{0.8, 0.8}, \ {1.2, 1.4}, \ rectplot]}]]; \)\)

DisplayFunction

DisplayFunction is an option for every graphics function in Mathematica. With it, we specify the output medium for the image. By default, this option is set to the global variable $DisplayFunction, which in the notebook front end, will render the graphic inside the current notebook. To send the PostScript output to a file use the setting DisplayFunction -> Display["file", #]&.

For our purposes the setting DisplayFunction -> Identity will be the most useful. This is because the graphic is computed, but not displayed. When you wish to display the graphic, you need to set DisplayFunction back to the default value, $DisplayFunction.

\(gr1 = 
      Plot[0.1\ x\^3 - 2\ x, {x, \(-10\), 10}, 
		
        PlotStyle -> {{RGBColor[1, 0, 0], \ Thickness[0.01]}}, 
		
        DisplayFunction -> Identity]; 

    gr2 = Plot[x\ Sin[x]\^2, {x, \(-10\), 10}, 
		
        PlotStyle -> {{GrayLevel[0.7]}}, 
		
        DisplayFunction -> Identity]; 

    Show[{gr1, gr2}, 
		DisplayFunction -> $DisplayFunction]; \)

When we are combining plots, usually we are only interested in the final graphic. If we had not set DisplayFunction to Identity in the previous example, Mathematica would have printed each component graphic also.

DisplayTogether and DisplayTogetherArray

The package Graphics`Graphics` which defines the functions DisplayTogether and DisplayTogetherArray, allows us to combine graphs on the same set of axes or in an array without rendering each graph beforehand. To use the functions we first load the package.

Needs["Graphics`Graphics`"]

\(\(DisplayTogether[
	
      Plot[Sin[x], {x, \(-3\), 3}, PlotStyle -> GrayLevel[0.5]], 
      Plot[Sin[3  x], {x, \(-3\), 3}, PlotStyle -> Dashing[{0.01}]]]; \)\)

DisplayTogetherArray[
      Plot[Sin[x], {x, -3, 3}, PlotStyle -> GrayLevel[0.5]], 
      Plot[Sin[3  x], {x, -3, 3}, PlotStyle -> Dashing[{0.01}]]];

It is important to note that DisplayTogether and DisplayTogetherArray do not work with graphics that we have named. If we have graphics that have already been assigned to a symbol name, we should use the Show function.

Graphics Formats

Mathematica generates graphics in PostScript form. In most Mathematica implementations you can see and edit the PostScript code directly. This form is transportable among all platforms and contains enough information to allow viewing and printing at any resolution or size.

We can save the PostScript to a file that can be read by many of the highest-quality graphics processors. For example, if we wanted to save a graphic as an Encapsulated PostScript file (EPS) for use in another graphics program, all we would have to do is select the graphic and choose the Save Selection As... command in the Edit menu of the front end and then choose which format we want from the submenu that appears.

The user has the ability to convert the graphic to any one of several local formats, depending on the platform that Mathematica runs on. Usually the results are a loss of generality but savings in speed (rendering) and space.

Image Conversions

Display[channel, graphics] writes graphics or sound to the specified output channel in Mathematica PostScript format. Display[channel, graphics, "format"] writes graphics or sound in the specified format. Display[channel, expr, "format"] writes boxes, cells, or notebook expressions in the specified format. channel specifies where the image is to be written. Using a filename, such as graph1.eps, will create a new file. The following formats are available.

({{EPS, Encapsulated PostScript}, {GIF, GIF}, {Illustrator, Adobe Illustrator format}, {Metafile, Microsoft Windows metafile}, {MGF, Mathematica system–independent raster graphics 
                format}, {MPS, Mathematica abbreviated PostScript}, {PCL, Hewlett–Packard printer control language}, {PDF, Adobe Acrobat portable document format}, {PICT, Macintosh PICT}, {PBM, portable bitmap}, {PSImage, PostScript image format}, {TIFF, TIFF}, {XBitmap, X Windows bitmap}})

Several different formats specific to other programs are also supported. In addition, on all platforms we can export a graphics as a DXF file, AutoCad’s standard. This functionality is in a Mathematica standard add-on package.

Enter Needs["Utilities`DXF`"] to load the package.

8. Using Options

Plot Options

Basics

Many aspects of every Mathematica graphic are controlled by the values of the options associated with it. Striking changes can be made by using these judiciously. Options[command ] lists all options for command and their defaults.

Options[ Plot] // TableForm

PlotRange and Domain

Besides the function we wish to plot, the only required parameter to the function Plot is the domain over which to plot the function. Given that information, Mathematica will choose a range to display in the final graphic. The x-range displayed by default will be exactly the specified domain, while the y-range displayed will be one chosen to display what Mathematica considers to be the interesting parts of the graph. Sometimes, though, extreme values will be cut off so that the rest of the graphic may be scaled normally.

Plot[x Sin[x]^3, {x, -10, 10}];

The option PlotRange allows us to specify the area of the graph to show. We may set this option to All to ensure that the entire graphic is displayed, or we may choose arbitrary coordinates. We may also specify the x range to display by giving coordinates in the form {{xmin, xmax}, {ymin, ymax}}. Note that the curve is computed only for the specified domain even if we display a larger one using PlotRange.

range1 = 
      Plot[x Sin[x]^3, {x, -10, 10}, PlotRange -> All, 
        DisplayFunction -> Identity];

range2 = 
      Plot[x Sin[x]^3, {x, -10, 10}, PlotRange -> {-10, 10}, 
        DisplayFunction -> Identity];

range3 = 
      Plot[x Sin[x]^3, {x, -10, 10}, 
        PlotRange -> {{-15, 15}, {-15, 15}}, 
        DisplayFunction -> Identity];

Show[GraphicsArray[{range1, range2, range3}]];

Adaptive Sampling Algorithm, PlotDivision, and PlotPoints

Mathematica uses an adaptive sampling algorithm to choose the points sampled in a two-dimensional plot. Beginning with 25 equally spaced points dividing the domain to be plotted, Mathematica looks at each set of three consecutive points and computes the angle between the line segment joining the first and second points and the line segment joining the second and third points. If this angle is close to 180 degrees, then Mathematica connects the points with lines. If not, Mathematica subdivides that interval and tries again. This allows Mathematica to sample more points in a “curvy” section of the function than in a flat section.

This process can be controlled by the options PlotDivision, which is the upper limit on the number of times an interval will be divided, and PlotPoints, which sets the initial number of points to be sampled.

Although this is a very robust algorithm, which produces accurate results in most cases, any scheme using a finite number of points is prone to miss sometimes. Here is an example of a function that is misplotted using the default number of plot points, but which can be accurately plotted by raising the initial number of plot points used.

Plot[x + Sin[2 π x], {x, 0, 25}];

Plot[x + Sin[2 π x], {x, 0, 24}, PlotPoints -> 50];

AspectRatio

The ratio of height to width of the plot is controlled with AspectRatio. The default value is the inverse of the golden ratio, or approximately 0.618. We may set this to an arbitrary real number for explicit control, or use the keyword Automatic to allow Mathematica to compute a realistic AspectRatio from the coordinate values in the plot. With this setting, circles and other geometric figures will appear proportionally correct. It is the default setting, historically the choice of artists and architects for their work, and Automatic that will be most often used.

aspect1 = 
      ParametricPlot[{Sin[t], Cos[t]}, {t, 0, 2 π}, 
        DisplayFunction -> Identity];

aspect2 = 
      ParametricPlot[{Sin[t], Cos[t]}, {t, 0, 2 π}, 
        AspectRatio -> Automatic, DisplayFunction -> Identity];

Show[GraphicsArray[{aspect1, aspect2}]];

PlotStyle

This option allows the user control over the way the curve itself is drawn. Since Plot allows us to graph an arbitrary number of curves simultaneously, PlotStyle takes a list of lists of directives, pairing each list of directives with one curve. If there are more curves than lists of directives, the existing lists of directives are applied cyclically.

The color of the curve can be specified in any of the standard ways. Thickness of the line is controlled by Thickness[r], where r is given as a fraction of the graphic’s total width or by AbsoluteThickness[d], where d is specified in points (where 1 point is (1/72) inch). We can create a dashed line with the directive Dashing[{(Subscript[r, 1]), (Subscript[r, 2]), … }], where {(Subscript[r, 1]), (Subscript[r, 2]), …} denote lengths of successive segments as a fraction of the total width of the graphic. The lengths are repeated cyclically. AbsoluteDashing[{(Subscript[d, 1]), (Subscript[d, 2]), … }] behaves identically but takes lengths in points. When plotting points with a function such as ListPlot, PointSize[r] specifies the radius of individual points, where r is given as a fraction of the graphic’s total width. AbsolutePointSize[r] allows specification of the radius r in points.

\(\(Plot[{2\ x\^2\ E\^\(-x\^2\), 2\ x\^2\ E\^\(\(-2\)\ x\^2\), 
        2\ x\^2\ E\^\(\(-3\)\ x\^2\)}, {x, \(-2\), 2}, 
	
      PlotStyle -> 

        		{{Red}, {Dashing[{0.03, 0.02}], Magenta}, \ {Thickness[0.013]}}, 
      
	PlotRange -> {\(-1\), 1}, PlotPoints -> 50]; \)\)

Frames, Axes, Labels, and Grids

By default, Mathematica will draw coordinate axes, but no frame and no labels, on a two-dimensional plot.

Plot[x (E^x) Sin[8 π x], {x, 0, 1}];

If we ask for a frame, the ticks are automatically drawn on the frame rather than through the graphic, so often we will want to turn off the axes entirely.

\(\(frame1 = 
      Plot[x\ E\^x\ Sin[8\ π\ x], {x, 0, 1}, 
		Frame -> True, 
        DisplayFunction -> Identity]; \)\)

\(\(frame2 = 
      Plot[x\ E\^x\ Sin[8\ π\ x], {x, 0, 1}, 
		Frame -> True, 
        Axes -> False, DisplayFunction -> Identity]; \)\)

Show[GraphicsArray[{frame1, frame2}]];

Axes allows is to control which, if any, axes are drawn, while AxesStyle controls how the axes are drawn. Axes can bet set to True or False, or to a list of values allowing us to control each axis independently. AxesStyle can take a list of lists of graphics directives and control the style of each axis independently. Analogous to AxesStyle, FrameStyle gives us control over the way the frame is drawn.

\(\(axes1 = 
      Plot[x\ E\^x\ Sin[8\ π\ x], {x, 0, 1}, 
		
        Axes -> {True, False}, DisplayFunction -> Identity]; \)\)

\(\(axes2 = 
      Plot[x\ E\^x\ Sin[8\ π\ x], {x, 0, 1}, 
		
        AxesStyle -> 

          			{{RGBColor[0, 1, 0], Thickness[0.02]}, {RGBColor[1, 0, 0], 
              Thickness[0.03]}}, DisplayFunction -> Identity]; \)\)

\(\(axes3 = 
      Plot[x\ E\^x\ Sin[8\ π\ x], {x, 0, 1}, 
		Frame -> True, 

        		Axes -> False, 
		
        FrameStyle -> {Thickness[0.02], RGBColor[0, 0, 1]}, 
        DisplayFunction -> Identity]; \)\)

Show[GraphicsArray[{axes1, axes2, axes3}]];

PlotLabel allows us to specify a title for the entire graphic, while FrameLabel allows labeling of each edge of the frame. (Note that while rotated text may not display correctly on the screen, it will print correctly.)

\(\(Plot[x\ E\^x\ Sin[8\ π\ x], {x, 0, 1}, 
	Frame -> True, 

      	Axes -> False, 
	PlotLabel -> "Exponential & Sine", 
      FrameLabel 
        -> {"Time", "Response", None, "Right Label"}]; \)\)

TextStyle will set the font for all text in the graphic. We may also use StyleForm to choose fonts individually.

\(\(font1 = 
      Plot[x\ E\^x\ Sin[8\ π\ x], {x, 0, 1}, 
		Frame -> True, 

        		Axes -> False, 
		PlotLabel -> "Sin[x]/x", 
		
        FrameLabel -> {"Time", "Response"}, 
		
        TextStyle 
          -> {FontFamily -> "Helvetica", FontSize -> 10}, 
        
		DisplayFunction -> Identity]; \)\)

\(\(font2 = 
      Plot[x\ E\^x\ Sin[8\ π\ x], {x, 0, 1}, 
		Frame -> True, 

        		Axes -> False, 
		
        PlotLabel -> 
          StyleForm[Sin[x]/x, 
				FontFamily -> "Times", 
            FontWeight -> "Bold", FontSize -> 14], 
		
        FrameLabel -> {"Time", "Response"}, 
		
        TextStyle 
          -> {FontFamily -> "Helvetica", FontSize -> 10}, 
        
		DisplayFunction -> Identity]; \)\)

Show[GraphicsArray[{font1, font2}]];

The RotateLabel option defaults to True allowing labels on vertical axes to be written parallel to the axis.

AxesOrigin allows us to specify the point in a two-dimensional graphic where the coordinate axes meet. If set outside the range of the plot, the axes will not cross at all.

\(\(origin1 = 
      Plot[x\ E\^x\ Sin[8\ π\ x], {x, 0, 1}, 
		
        AxesOrigin -> {0.5, 0.5}, 
		Ticks -> {Automatic, None}, 
        
		DisplayFunction -> Identity]; \)\)

\(\(origin2 = 
      Plot[x\ E\^x\ Sin[8\ π\ x], {x, 0, 1}, 
		
        AxesOrigin -> {0.2, 1}, 
		DisplayFunction -> Identity]; 
    \)\)

Show[GraphicsArray[{origin1, origin2}]];

GridLines allows us to specify the placement of a grid under the graphic. The default setting is None. A setting of Automatic will generate uniformly spaced grid lines in both directions, or we can specify the actual positions by giving a list of values. We may specify different grid lines in each direction with the format {xgrid, ygrid}.

grid1 = 
      Plot[Sin[x]/x, {x, -10, 10}, GridLines -> Automatic, 
        DisplayFunction -> Identity];

grid2 = 
      Plot[Sin[x]/x, {x, -10, 10}, 
        GridLines -> {{-10, -5, -2.5, 2.5, 5, 10}, None}, 
        DisplayFunction -> Identity];

grid3 = 
      Plot[Sin[x]/x, {x, -10, 10}, 
        GridLines -> {Range[-10, 10], Automatic}, 
        DisplayFunction -> Identity];

Show[GraphicsArray[{grid1, grid2, grid3}]];

Colors

With Background, DefaultColor, and PlotStyle we control the colors of various aspects of the graphic. Note that we explicitly load the Graphics`Colors` package so that we may use names instead of RGB specifications. DefaultColor, the color to use for lines, points, tick marks, etc., can be set to any valid color specification. When set to Automatic, a color complementary to the color of the background, which can be set with Background, is used.

Needs["Graphics`Colors`"]

\(\(Plot[2\ x\^5 - 3\ x\^4 + 10\ x\^2 - 2\ x - 1, {x, \(-2\), 2}, 
	
      Background -> SkyBlue, 
	DefaultColor -> RosyBrown, 
	
      PlotStyle -> {{Thickness[0.02], Maroon}}]; \)\)

Spacing

PlotRegion allows us to specify how much blank space to leave around the graphic. A setting of the form {{sxmin, sxmax}, {symin, symax}} specifies the region, in scaled coordinates, that the plot should fill in the final display area. When set to Automatic, the plot will fill the final display area.

defaultregion = 
      Plot[2 (x^5) - 3 (x^4) + 10 (x^2) - 2 x - 1, {x, -2, 2}, 
        Background -> SkyBlue, 
        PlotLabel -> 
          StyleForm["Quintic", FontFamily -> "Times", 
            FontWeight -> "Bold", FontSize -> 14], 
        DisplayFunction -> Identity];

largerregion = 
      Plot[2 (x^5) - 3 (x^4) + 10 (x^2) - 2 x - 1, {x, -2, 2}, 
        Background -> SkyBlue, 
        PlotLabel -> 
          StyleForm["Quintic", FontFamily -> "Times", 
            FontWeight -> "Bold", FontSize -> 14], 
        PlotRegion -> {{0.1, 0.9}, {0.1, 0.9}}, 
        DisplayFunction -> Identity];

Show[GraphicsArray[{defaultregion, largerregion}]];

Plot3D Options

Basics

Many of the options controlling three-dimensional graphics are identical to those used in the two-dimensional case.

AspectRatio, Background,  DefaultFont, PlotLabel, DefaultColor, and AxesStyle are options that are used identically with Plot3D and Plot, while AxesLabel, AxesStyle, PlotRange, and PlotRegion are called identically but extended to three dimensions via the addition of a third coordinate.

Point Sampling

Unlike Mathematica’s two-dimensional plotting algrorithm, three-dimensional plots have no built-in method for sampling more points where necessary to achieve an accurate plot. Plot3D will choose uniformly distributed points along the x-range and the y-range and plot only these values. The option PlotPoints, with default value 15, sets the number of divisions to use. PlotPoints can also be set to an ordered pair, denoting the number of points to use in each direction.

Plot3D[Sin[x - Cos[y]], {x, -3, 3}, {y, -3, 3}, 
      PlotPoints -> {10, 35}];

Lighting, Color, and Other Drawing Options

When plotting in three dimensions, several more color options are available.

AmbientLight and LightSources allow us to shade the three-dimensional graphic with external light. AmbientLight is by default white but can be set to any gray level or color specification. By setting a higher gray level, the graphics appears light and washed-out.

Plot3D[Sin[x - Cos[y]], {x, -3, 3}, {y, -3, 3}, 
      AmbientLight -> SlateGray];

LightSources allows us to create an arbitrary number of lights in arbitrary colors and shine them from arbitrary locations. By default, one red, one green, and one blue light shine from  the points {1., 0., 1.},  {1., 1., 1.},  and {0., 1., 1.}, respectively. Here we plot a surface with two light sources shining on it, one green and one blue.

Plot3D[Sin[x - Cos[y]], {x, -3, 3}, {y, -3, 3}, 
      LightSources -> {{{-1, 0, 1}, Green}, {{1, 0, 1}, Blue}}];

A more direct way of applying color to a surface is via the ColorFunction option. ColorFunction specifies a function to apply to function z values to determine the color of a particular x-y region. Since Hue, when called with only one argument, will run cyclically through the entire color wheel, it is suitable for use with ColorFunction.

cf1 = 
      Plot3D[Sin[x y], {x, -3, 3}, {y, -3, 3}, 
        ColorFunction -> Hue, PlotPoints -> 20, 
        DisplayFunction -> Identity];

mycolor[z_] := RGBColor[Random[], Random[], Random[]];

cf2 = 
      Plot3D[Sin[x y], {x, -3, 3}, {y, -3, 3}, 
        ColorFunction -> mycolor, PlotPoints -> 20, 
        DisplayFunction -> Identity];

We may also turn off the lighting altogether.

cf3 = 
      Plot3D[Sin[x y], {x, -3, 3}, {y, -3, 3}, 
        Lighting -> False, PlotPoints -> 20, 
        DisplayFunction -> Identity];

Show[GraphicsArray[{cf1, cf2, cf3}]];

We may also specify a function to apply to each x-y pair to indicate the color of each region. Use the format Plot3D[{f, s}, {x, xmin, xmax}, {y, ymin, ymax}], where s is the shading function. s can be any expression that yields a valid color specification.

shade1 = 
      Plot3D[{Sin[(Sqrt[(x^2) + (y^2)])], Blue}, {x, -3, 3}, {y, -3, 3}, 
        PlotPoints -> 20, DisplayFunction -> Identity];

shade2 = 
      Plot3D[{Sin[(Sqrt[(x^2) + (y^2)])], If[Sin[x - Cos[y]] > 0.5, Blue, Red]}, {
          x, -3, 3}, {y, -3, 3}, PlotPoints -> 20, 
        DisplayFunction -> Identity];

shade3 = 
      Plot3D[{Sin[(Sqrt[(x^2) + (y^2)])], 
          RGBColor[Abs[(x/3)], Abs[(y/3)], Abs[((x + y)/6)]]}, {x, -3, 
          3}, {y, -3, 3}, PlotPoints -> 20, 
        DisplayFunction -> Identity];

Show[GraphicsArray[{shade1, shade2, shade3}]];

A related option is ClipFill, which determines how to render areas of the surface that extend beyond the bounding box. By default, these areas are drawn as the rest of the surface. Setting ClipFill to None will show holes in these areas. We may specify one color for all clipped region or a pair of colors, one for the top and one for the bottom.

cf1 = 
      Plot3D[2 Sin[x - Cos[y]], {x, -3, 3}, {y, -3, 3}, 
        PlotRange -> {-1, 1}, DisplayFunction -> Identity];

cf2 = 
      Plot3D[2 Sin[x - Cos[y]], {x, -3, 3}, {y, -3, 3}, 
        ClipFill -> None, PlotRange -> {-1, 1}, 
        DisplayFunction -> Identity];

cf3 = 
      Plot3D[2 Sin[x - Cos[y]], {x, -3, 3}, {y, -3, 3}, 
        ClipFill -> {GrayLevel[.5], RGBColor[0, 1, 0]}, 
        PlotRange -> {-1, 1}, DisplayFunction -> Identity];

Show[GraphicsArray[{cf1, cf2, cf3}]];

By setting the option HiddenSurface to False, we can see the graphic rendered with transparent polygons.

Plot3D[2 Sin[x - Cos[y]], {x, -3, 3}, {y, -3, 3}, 
      HiddenSurface -> False];

Box, Mesh, and Other Extrinsic Details

Mesh and Boxed may be set only to True or False, and do the obvious things. Since the mesh on the surface simply connects the points plotted by Mathematica, its fineness is controlled by the value of PlotPoints.

Plot3D[Sin[x - Cos[y]], {x, -3, 3}, {y, -3, 3}, 
      Boxed -> False, Mesh -> False];

MeshStyle and BoxStyle allow control of the way these lines are drawn. They take graphics directives as arguments.

Plot3D[Sin[x - Cos[y]], {x, -3, 3}, {y, -3, 3}, 
      BoxStyle -> {Red, Thickness[0.02]}, 
      MeshStyle -> {Thickness[0.01]}];

FaceGrids allows us to specify whether to draw grids on the faces of the bounding box and to specify the arrangement of the grid. All and None are the simplest values for this option, but we may choose individual faces and arrange the grid lines. A face is specified by {(Subscript[dir, x]), (Subscript[dir, y]), (Subscript[dir, z])}, where two of the elements are 0 and the third is either +1 or –1. The form  {(Subscript[face, 1]),  (Subscript[face, 2]), … } is used to specify individual faces, and the form {{(Subscript[face, 1]), {xgrid, ygrid}}, … } is used to specify the grid for individual faces. Grid specifications follow the same format as that of GridLines, so complex styled grids can be drawn.

fg1 = 
      Plot3D[Sin[x - Cos[y]], {x, -3, 3}, {y, -3, 3}, 
        FaceGrids -> All, DisplayFunction -> Identity];

fg2 = 
      Plot3D[Sin[x - Cos[y]], {x, -3, 3}, {y, -3, 3}, 
        FaceGrids -> {{0, -1, 0}, {0, 0, 1}}, 
        DisplayFunction -> Identity];

fg3 = 
      Plot3D[Sin[x - Cos[y]], {x, -3, 3}, {y, -3, 3}, 
        FaceGrids 
          -> {{{0, -1, 0}, {
                Table[{i, RGBColor[1, 0, 0]}, {i, -3, 3, .25}], 
                Table[{i, RGBColor[0, 0, 1]}, {i, -1, 1, .4}]}}}, 
        DisplayFunction -> Identity];

Show[GraphicsArray[{fg1, fg2, fg3}]];

AxesEdge allows control over which three edges of the bounding box the axes are drawn, with specifications given in the form {{xdir, ydir}, {xdir, zdir}, {xdir, ydir}}, with each element being either 1 or –1, indicating whether to draw the axes on the edge of the box with the larger or smaller coordinate — the default being to draw toward the smaller coordinate. Any pair can be replaced by Automatic or None.

Plot3D[Sin[x - Cos[y]], {x, -3, 3}, {y, -3, 3}, 
      AxesEdge -> {Automatic, {-1, 1}, None}];

ViewPoint and Related Options

The point in space from which a three-dimensional object is viewed, the ViewPoint, is by default {1.3, –2.4, 2.0} but can be set to any triple. Notebook front ends to Mathematica all have a graphical viewpoint selector, which allows the user to select an orientation visually instead of numerically.

Plot3D[Sin[x - Cos[y]], {x, -3, 3}, {y, -3, 3}, 
      ViewPoint -> {10, 2, 1}];

ViewCenter allows us to specify where the center of the bounding box is, while ViewVertical specifies the direction in the image that should be vertical. In the following example, the positive y axis is vertical.

v1 = 
      Plot3D[Sin[x - Cos[y]], {x, -3, 3}, {y, -3, 3}, 
        ViewCenter -> {1, 0, 0}, DisplayFunction -> Identity];

v2 = 
      Plot3D[Sin[x - Cos[y]], {x, -3, 3}, {y, -3, 3}, 
        ViewVertical -> {0, 1, 0}, DisplayFunction -> Identity];

Show[GraphicsArray[{v1, v2}]];

BoxRatios is similar to AspectRatio but allows control over the ratios of the lengths of all three sides of the bounding box.

Plot3D[Sin[x - Cos[y]], {x, -3, 3}, {y, -3, 3}, 
      BoxRatios -> {9, 4, 1}];

By default, the option SphericalRegion is False, allowing the graphic to be drawn as large as possible. By setting it to True, we require that the image be scaled so that a sphere drawn around the bounding box will still fit in the display area. This control is useful when creating animations. Since Mathematica will try to make each graphic as large as possible, multiple graphics generated to create a movie may be drawn to different scales, ruining the effect of the animation. Setting SphericalRegion to True guarantees that all frames will be drawn the same size.

ContourPlot and DensityPlot Options

ContourPlot and DensityPlot generally take options available in Plot and Plot3D. The only exceptions are several options dealing specifically with ContourPlot. ContourLines controls the drawing of explicit contour lines. By default, this option is True. Contours allows us to choose the specific contours plotted. This option may be set to an integer n, which will produce n equally spaced contours between the minimum and maximum z values, or to an explicit list of z values. The style in which contour lines are drawn is specified in ContourStyle.

ContourPlot[Sin[x - Cos[y]], {x, -3, 3}, {y, -3, 3}, 
      ContourLines -> False, Contours -> 20];

ContourShading defaults to True. Setting it to False will leave the areas between contour lines blank. ContourShading also lets us specify the color between contour lines by using a list of color specifications.

\(\(ContourPlot[\ Sin[x] - Cos[y], \ {x, \(-2\), 2}, {y, \(-2\), 2}, 

      \ \ \ \ \ \ \ \ ContourShading\  -> \ {Hue[0.25], GrayLevel[0.25]}]; 
    \)\)

ParametricPlot and ParametricPlot3D Options

ParametricPlot has the same list of options as Plot.

ParametricPlot[{t Cos[t], t Sin[t]}, {t, 0, 4 π}, 
      PlotStyle -> {{RGBColor[0, 1, 0], Dashing[{0.02}]}}, 
      Frame -> True, Axes -> False, AspectRatio -> Automatic, 
      FrameStyle -> {Thickness[0.02], RGBColor[0.4, 0.2, 0.1]}];

ParametricPlot3D has a few minor differences from Plot3D. ParametricPlot3D lacks the options Mesh, MeshStyle, and HiddenSurface, and has one new option, RenderAll.

Large graphics can take a large amount of RAM to display— sometimes more memory than is available, especially if we are trying to create an animation in which each frame is a complicated Mathematica graphic.

RenderAll, an option for Graphics3D and ParametricPlot3D, which is True by default, allows the option of generating PostScript only for those polygons that will be visible in the final image. The resulting image contains significantly less PostScript code and therefore takes less memory to display and renders faster, but requires considerably more time to create.

Ticks

Although Mathematica will usually supply useful tick marks on graphics, much customization is possible. Ticks is an option for all graphics functions. With Ticks -> None, no tick marks are drawn on the axes. With Ticks -> Automatic, tick marks are placed automatically. Ticks -> {xticks, yticks, … } specifies tick mark options separately for each axis.

Plot[BesselJ[1, x], {x, 0, 10}, Ticks -> {None, Automatic}];

There are several levels of detail at which we may specify the properties of tick marks. The simplest is to supply a list of positions. Note that the list of positions can be generated by a Range or Table command, though this method may be limiting should we change the domain used in the plot.

Plot[BesselJ[1, x], {x, 0, 10}, 
      Ticks -> {{0, 2, 4, 6, 7, 8, 9, 10}, Range[-0.2, 0.5, 0.1]}];

We may also specify the label associated with each tick mark, the length of the mark (both how far above and below the axes it extends), and the style in which to draw the mark. The following is a list of allowable configurations for a tick mark. Note that you may vary among these throughout one list of tick marks.

({{position}, {{position, label}}, {{position, label, length}}, {{position, label, length, {style}}}, {{position, label, {positive length, negative length}}}, {{position, label, {positive length, negative length}, {style}}}})

Plot[ BesselJ[1, x], {x, 0, 10}, 
Ticks ->
{{{1.8,"max", 0.05,{Thickness[0.01],Red}},
  {5.3,"min", 0.05,{Thickness[0.01],Red}},
  {8.5,"max", 0.05,{Thickness[0.01],Red}}},
 {{-0.35,"mark ",{0,0.02},{Thickness[0.01],Blue}},
  {0.58,"mark ",{0,0.02},{Thickness[0.01],Blue}},
  {0.28,"mark ",{0,0.02},{Thickness[0.01],Blue}} } }];

In this way we can add explicitly known information to a graphic, but Ticks is also designed to work in a more general fashion. Ticks can take as its arguments functions that take as arguments the minimum and maximum range for an axis and return a valid tick specification. Using this form, the specifications are not tied to explicit ranges. Here we define two tick specifications. Each function draws unlabeled blue ticks every unit and larger, labeled blue ticks every 5 or 10 units, respectively.

myticks5[min_, max_] :=
	Join[
		Table[{x, x, 0.05, {RGBColor[0,0,1]}}, 
					{x, 0, Ceiling[max],5}],
		Table[{x, x, 0.05, {RGBColor[0,0,1]}}, 
					{x,0, Floor[min],-5}],
		Table[{x, "", 0.02, {RGBColor[0,0,1]}}, 
					{x, Floor[min], Ceiling[max]}]
		];

myticks10[min_, max_] :=
	Join[
		Table[{x, x, 0.05, {RGBColor[0,0,1]}}, 
					{x, 0, Ceiling[max],10}],
		Table[{x, x, 0.05, {RGBColor[0,0,1]}}, 
					{x,0, Floor[min],-10}],
		Table[{x, "", 0.02, {RGBColor[0,0,1]}}, 
					{x, Floor[min], Ceiling[max]}]
		];

\(\(Plot[x\ Sin[0.3\ π\ x]\^2, {x, \(-20\), 20}, 
	
      Ticks -> {myticks10, myticks5}, 
	PlotPoints -> 75]; \)\)

Show[%, PlotRange -> {{-30, 30}, {-25, 25}}];

When a frame is drawn around the plot, FrameTicks is used to specify ticks to be drawn on the frame. FrameTicks takes the same arguments as Ticks.

\(\(Plot[x\ Sin[0.3\ π\ x]\^2, {x, \(-20\), 20}, 
	
      Frame -> True, 
	
      FrameTicks -> {myticks10, myticks5, None, None}]; \)\)

We use exactly the same specifications for three-dimensional plots, contour plots, and density plots.

Plot3D[0.25 Cos[0.03 x y], {x, -30, 30}, {y, -30, 30}, 
      PlotPoints -> 20, 
      Ticks -> {myticks10, myticks10, Automatic}];

Prolog, Epilog, and Rectangle

Epilog is an option to every graphics function that allows arbitrary graphics to be rendered after the main graphic has been rendered. Prolog specifies arbitrary graphics primitives and directives to be rendered before the main graphics is rendered. For simplicity, we will look only at Epilog.

Any two-dimensional graphic can be superimposed on any two-dimensional plot. Arrow, Text, and several graphics directives can be combined to add information to this plot. We can specify the font by using StyleForm within a Text primitive.

\(\(Plot[4\ x\^2 + 12\ x - 10, {x, \(-10\), 10}, 
	
      Epilog -> {
			
          Text[StyleForm["Ω", FontSize -> 18, 
              FontWeight -> "Bold"], {0, 600}], 
          Text[StyleForm["Δ", FontSize -> 18, 
              FontWeight -> "Bold"], {12, 0}]}, 
	
      PlotRange -> All]; \)\)

\(\(Plot[x\ Sin[0.9\ x]\^2, {x, \(-10\), 10}, 
      Epilog -> {
			RGBColor[1, 0.5, 0.6], 
			
          Text[StyleForm["Minima", 
					
              FontFamily -> "Helvetica", 
              FontWeight -> "Bold", FontSize -> 12], {6, 
              \(-8.5\)}], 
          Text[StyleForm["Maxima", 
					
              FontFamily -> "Helvetica", 
              FontWeight -> "Bold", FontSize -> 12], {\(-6\), 
              8.5}], 
			RGBColor[0, 0, 1], 
			
          Arrow[{\(-6\), 7}, {\(-7\), 0}], Arrow[{\(-6\), 7}, {\(-3.5\), 0}], 
          Arrow[{\(-6\), 7}, {2, 2}], Arrow[{\(-6\), 7}, {5.25, 5.45}], 
          Arrow[{\(-6\), 7}, {8.75, 8.9}], 
          Arrow[{6, \(-7\)}, {\(-8.8\), \(-8.75\)}], 
          Arrow[{6, \(-7\)}, {\(-5.35\), \(-5.25\)}], 
          Arrow[{6, \(-7\)}, {\(-2.1\), \(-1.85\)}], 
          Arrow[{6, \(-7\)}, {3.5, 0}], Arrow[{6, \(-7\)}, {7, 0}]}]; \)\)

More generally, we can include any graphic in any other graphic using Rectangle. The form Rectangle[{xmin, ymin}, {xmax, ymax}] represents a filled rectangle oriented parallel to the axes. The more general form Rectangle[{xmin, ymin}, {xmax, ymax}, graphics] represents a rectangle filled with the arbitrary graphics.

\(\(inset = 
      Plot[Sin[x]\/x, {x, \(-10\), 10}, 
		Frame -> True, 
		
        Ticks -> None, 
		FrameTicks -> None, 
		
        FrameStyle -> {GrayLevel[.5], Thickness[0.03]}, 
		
        PlotStyle -> {{Dashing[{0.04}]}}, 
		
        DisplayFunction -> Identity]; \)\)

\(\(Plot[x\ Sin[x]\^2, {x, \(-10\), 10}, 
	
      PlotStyle -> RGBColor[0, 0, 1], 
      Epilog -> Rectangle[{\(-9\), 3}, {\(-2\), 8}, inset]]; \)\)

We can create functions which return graphics objects. Below is a function called CircledDigit, which creates labels we can place on any graphic.

\(CircledDigit[d_String, {x_, y_}] := 

      	{Hue[0], Disk[{x, y}, 0.9], GrayLevel[1], Text[d, {x, y}]}\)

\(\(Plot[x\ Sin[x]\^2, {x, \(-10\), 10}, 
	
      Epilog -> {
			CircledDigit["1", {4.9, 5}], 
			
          CircledDigit["2", {\(-9.4\), 0.5}]}, 
	
      AspectRatio -> Automatic]; \)\)

9. Animations

Creating Animations in Notebooks

All versions of Mathematica can create animations. Animation results when a series of Mathematica graphics are displayed quickly in succession to create the illusion of smooth movement.

Mathematica provides many features to aid this process. Here is a simple example. The command Table creates an array of results by iterating commands. Here we will create ten different plots of Sin[a  x ], letting a vary. Notice that we explicitly set a PlotRange because the default for Mathematica is to pick a new PlotRange for each frame of the animation, which could ruin the animation effect.

\(\(Table[
	
      Plot[Sin[a\ x], {x, 0, 10}, PlotRange -> {{0, 10}, {\(-1\), 1}}], {
        a, 1, 5, 0.5}]; \)\)

(The cells of the animation have been deleted to save space. Enter the code into Mathematica to see the animation.)

If you have three-dimensional graphics with different viewpoints, you should similarly set SphericalRegion to be True to ensure that the scaling of different plots are the same.

Table[
      Plot3D[(2 + Sin[x]) Cos[2 y], {x, -2, 2}, {y, -3, 3}, 
        BoxRatios -> {1, 5, 1}, Boxed -> False, Axes -> False, 
        ViewPoint -> {a, 1, 1}], {a, 0, 1, 0.1}];

(The cells of the animation have been deleted to save space. Enter the code into Mathematica to see the animation.)

Although all that is necessary to create an animation in Mathematica is a series of graphics, a number of animation functions are defined in the package Graphics`Animation`.

Needs["Graphics`Animation`"]

?Graphics`Animation`*

MoviePlot[ f[x, t], {x, (Subscript[x, 0]), (Subscript[x, 1])}, {t, (Subscript[t, 0]), (Subscript[t, 1])} ] will animate plots of f[x, t] regarded as a function of x, with t serving as the animation (or time) variable.

MoviePlot[Sin[a x], {x, 0, 10}, {a, 1, 5, 0.5}]

(The cells of the animation have been deleted to save space. Enter the code into Mathematica to see the animation.)

Notice that MoviePlot is essentially a shortcut for using the Table command. One difference is that MoviePlot automatically uses the same PlotRange for each frame.

Another interesting animation results by varying the viewpoint, thereby creating a revolution or a flyby of an object. SpinShow automates this process.

\(\(SpinShow[\ Graphics3D[\ Stellate[\ Icosahedron[]\ ]\ ], 
	
      Boxed -> False]; \)\)

(The cells of the animation have been deleted to save space. Enter the code into Mathematica to see the animation.)

Other effects can be achieved by varying colors, options, ranges, and so on.

MathLive

MathLive is a real-time visualization environment that can be used with graphics generated within Mathematica.

As we have seen, Mathematica animations are a collection of frames that are viewed in succession to give the impression of  motion. MathLive allows us to load a graphics object created in Mathematica from a file or directly through a MathLink connection and manipulate the object in real time.

Files

You can use MathLive with files in various ways. One is the 3-Script file interface to Mathematica.  Using the ThreeScript package, you can write a representation of three-dimensional graphics to a standard text file format.  This may be read directly into MathLive.  However, because of the limitations of the 3-Script format, you will normally find that the use of MathLink  is preferable, since considerably more information about the surface can be passed directly via MathLink. Another type of file is the texture file, which allows you to add textures to your graphics. MathLive also has its own file type called an ASCII mesh file. MathLive scenes can be saved in this format and reloaded later in new sessions of MathLive.

Needs["Graphics`ThreeScript`"]

\(\(bell = 
      Plot3D[Exp[\(-x\^2\) - y\^2], {x, \(-2\), 2}, {y, \(-2\), 2}, 
		
        PlotPoints -> 25, \ Boxed\  -> \ False, \ 
        Axes\  -> \ False]; \)\)

ThreeScript["bell.ts",  bell]

Once we have a 3-Script file, we can launch MathLive and open the file.

Using MathLive with MathLink

MathLive has been developed to handle the MathLink communications standard for direct communication to Mathematica.  By using MathLink, graphics may be sent directly from Mathematica to MathLive. This method is faster and easier than using 3-Script files.

First we need to tell Mathematica where MathLive resides.

$LivePath  =  
      "Red:Mathematica Files:Application Libraries:MathLive:MathLive"

Then we can open the MathLink connection in one of two ways. The first is to have Mathematica launch MathLive for us.

live  =  LinkOpen[$LivePath,  LinkMode  ->  Launch];

Or we can connect to MathLive directly, if we have already launched it manually.

live  =  LinkOpen["MathLive",  LinkMode  ->  Connect];

Once the MathLink connection is open, we can send three-dimensional graphics to MathLive to be manipulated.

\(\(lumpy = 
      Plot3D[Sin[x\^2]\ Sin[y\^2], {x, \(-π\), π}, 
        \ {y, \(-π\), π}, 
		PlotPoints -> 30, \ 
        Boxed\  -> \ False, \ Axes\  -> \ False]; \)\)

LinkWrite[live,  lumpy];

Now the graphic we called lumpy has been sent to MathLive.

Capabilities

Once we have a graphic in MathLive there are a number of ways we can view and manipulate it. First, just by clicking on the graphic and moving the mouse, we can impart rotation in the direction that we moved the mouse with the speed of the rotation relative to how fast we moved the mouse.

We can also manipulate how the graphic is visualized and how we view the graphic with commands built into MathLive. For instance, we can change the surface lighting, make the surface solid or wire frame, or map a texture onto the graphic.

Some of the different animations available include rotating or tilting the camera, flying past the graphic or doing corkscrews around the graphic, and varying the lighting around the graphic.

Animations can also be exported into QuickTime files.

Using Table, Do, or MoviePlot, create a two-dimensional animation of a function that changes over time. Be sure that the domain and range remain the same throughout the animation.

myanim = 
      Table[Plot[Sin[k x], {x, 0, 3 π}, 
          PlotRange -> {{0, 10}, {-1, 1}}, PlotPoints -> 50], {
          k, 1, 12}];

The line above will generate the animation, but for better viewing on the printed page, we use GraphicsArray to view all the frames at once.

Show[GraphicsArray[Partition[myanim, 3]]];

Choose your favorite three-dimensional graphic from this set of exercises (or make a new one) and create an animation using SpinShow. (Remember to load the Graphics`Animation` package first!)

Needs["Graphics`Animation`"]

\(\(simpleplot3d = 
      Plot3D[Sin[x - Cos[y]], {x, \(-3\), 3}, {y, \(-3\), 3}, 
		
        Boxed -> False, Axes -> False]; \)\)

my3danim = SpinShow[simpleplot3d, Frames -> 12]

(The cells of the animation have been deleted to save space. Enter the code into Mathematica to see the animation.)

10. Creating Graphics Functions

There are times when we will want to create a specific type of plot that Mathematica does not directly support. We can eventually make up any kind of graphics we want within Mathematica. Sometimes we’ll be pleasantly surprised to find out that what we want is just a variant of a type of plot Mathematica already knows, other times we will have to start from the basic building blocks of points and lines.

InequalityPlot

Basis

As an exercise, we will use Mathematica to create a flexible function that will draw inequality plots; that is, plots where the area above or below the curve are shaded.

To create an inequality plot seems dificult until we realize that we can already achieve the desired results fairly easily using ContourPlot. ContourPlot[f, {x, xmin, xmax}, {y, ymin, ymax}]generates a contour plot of f as a function of x and y. Several options allow us to change ContourPlot into what we need. Contours is an option that lists the specific contours to plot. For example, the following example specifically draws contours that are the solutions to 4  (x^2) - y = 1, 4  (x^2) - y = 2, and 4  (x^2) - y = 3. Note that by default Mathematica shades the areas between the contour lines.

\(\(ContourPlot[4\ x\^2 - y, {x, \(-3\), 3}, {y, \(-3\), 3}, 
	
      Contours -> {1, 2, 3}]; \)\)

When we tell Mathematica to draw only the contour at 0, the resulting graph represents 4  (x^2) - y < 0, which can be rewritten 4  (x^2) < y.

\(\(ContourPlot[4\ x\^2 - y, {x, \(-3\), 3}, {y, \(-3\), 3}, 
	
      Contours -> {0.}, PlotPoints -> 50]; \)\)

What remains is to define a new function that accepts inequalities as input and translates that format into a standard ContourPlot command, and then to add appropriate options to our new function. We'll call our new function InequalityPlot, and we will want it to transform something that looks like a < b into a - b. The prefix form of a < b is Less[a,b], so we tell InequalityPlot to expect input in this form. We also require the user to give an x- and y-range to the function, which is passed on to ContourPlot. To give the user control over all of the ContourPlot options, we include an argument for arbitrary options.

\(\(InequalityPlot[a_ < b_, xrange_List, yrange_List, opts___] := 
      ContourPlot[a - b, xrange, yrange, 
		PlotPoints -> 45, 
        Contours -> {0.}, opts]; \)\)

InequalityPlot[(x^2) < y, {x, -3, 3}, {y, -3, 3}];

Creating our own coloring function that will return gray inside the area bounded by the curve and white outside will make this start to look like a “finished” graphic.

\(Clear[InequalityPlot, mycolorfunction]; 
    mycolorfunction[x_] := If[x == 0, GrayLevel[0.5], GrayLevel[1]]; 


    InequalityPlot[a_ < b_, xrange_List, yrange_List, opts___] := 
      ContourPlot[a - b, xrange, yrange, 
		PlotPoints -> 45, 
        Contours -> {0.}, ColorFunction -> mycolorfunction, opts]; 
    \)

InequalityPlot[(x^2) < y, {x, -3, 3}, {y, -3, 3}];

To make this look more like the inequalities we graphed in school, we should move the axes to the center of the graph and remove the frame.

\(Clear[InequalityPlot, mycolorfunction]; 
    mycolorfunction[x_] := If[x == 0, GrayLevel[0.5], GrayLevel[1]]; 


    InequalityPlot[a_ < b_, xrange_List, yrange_List, opts___] := 
	
      ContourPlot[a - b, xrange, yrange, 
		PlotPoints -> 45, \ 
        Contours -> {0.}, 
		ColorFunction -> mycolorfunction, 
        Frame -> False, 
		Axes -> True, 
        AxesOrigin -> {0, 0}, opts]; \)

InequalityPlot[(x^2) < y, {x, -3, 3}, {y, -3, 3}];

This didn’t quite work as expected, since the axes are now hidden behind the graph. Recall that FilledPlot has an option AxesFront that takes care of this problem. Looking at the package we see that what the author did was define the option AxesFront for Graphics. If we load this package, we can make use of this solution for our function. Since AxesFront is an option for graphics functions and not plotting functions, we must rearrange our function to create a graphics object and then use Show to display it with the AxesFront option set to True.

Needs["Graphics`FilledPlot`"]

\(Clear[InequalityPlot, mycolorfunction]; 
    mycolorfunction[x_] := If[x == 0, GrayLevel[0.5], GrayLevel[1]]; 


    InequalityPlot[a_ < b_, xrange_List, yrange_List, opts___] := 
      Show[Graphics[
          ContourPlot[a - b, xrange, yrange, 
		PlotPoints -> 45, 
            Contours -> {0.}, 
		
            ColorFunction -> mycolorfunction, Frame -> False, 
		
            Axes -> True, AxesOrigin -> {0, 0}, 
		
            DisplayFunction -> Identity, opts]], 
	
        AxesFront -> True, DisplayFunction -> $DisplayFunction]; 
    \)

InequalityPlot[(x^2) < y, {x, -3, 3}, {y, -3, 3}];

Note that we haven’t given the function a way to accept other forms, such as a > b, a ≤ b, etc. Of course, the user can insert a minus sign in the appropriate place, but we can easily automate this feature by providing several cases in our definition. Using patterns so that Mathematica treats various inputs differently is one of the most powerful techniques available within Mathematica. We also customize the way the curve is drawn using ContourStyle, drawing a dashed line when “<” is used and solid line when “≤” is used.

Final InequalityPlot Code

Needs["Graphics`Master`"]

\(Clear[InequalityPlot, mycolorfunction]; 
    mycolorfunction[x_] := If[x == 0, GrayLevel[0.5], GrayLevel[1]]; 


    SetOptions[ContourPlot, 
		\ PlotPoints -> 45, 
		\ 
      Contours -> {0.}, 
		\ Frame -> False, 
		\ 
      Axes -> True, 
		\ AxesOrigin -> {0, 0}, 
		\ 
      DisplayFunction -> Identity]; 


    InequalityPlot[a_ < b_, xrange_List, yrange_List, opts___] := 
      Show[Graphics[
          ContourPlot[a - b, xrange, yrange, opts, 
		
            ColorFunction -> mycolorfunction, 
		
            ContourStyle 
              -> {Thickness[0.02], RGBColor[1, 0, 0], 
                Dashing[{0.04}]}]], opts, AxesFront -> True, 
        DisplayFunction -> $DisplayFunction]; 


    InequalityPlot[a_ > b_, xrange_List, yrange_List, opts___] := 
      Show[Graphics[
          ContourPlot[\(-\((a - b)\)\), xrange, yrange, opts, 
		
            ColorFunction -> mycolorfunction, 
		
            ContourStyle 
              -> {Thickness[0.02], RGBColor[1, 0, 0], 
                Dashing[{0.04}]}]], opts, AxesFront -> True, 
        DisplayFunction -> $DisplayFunction]; 


    InequalityPlot[a_ ≥ b_, xrange_List, yrange_List, opts___]
         := 
	Show[
        Graphics[
          ContourPlot[\(-\((a - b)\)\), xrange, yrange, opts, 
		
            ColorFunction -> mycolorfunction, 
		
            ContourStyle -> {Thickness[0.02], RGBColor[1, 0, 0]}]], 
        opts, AxesFront -> True, 
        DisplayFunction -> $DisplayFunction]; 


    InequalityPlot[a_ ≤ b_, xrange_List, yrange_List, opts___] := 
      
	Show[Graphics[
          ContourPlot[a - b, xrange, yrange, opts, 
		
            ColorFunction -> mycolorfunction, 
		
            ContourStyle -> {Thickness[0.02], RGBColor[1, 0, 0]}]], 
        opts, AxesFront -> True, 
        DisplayFunction -> $DisplayFunction]; 


    InequalityPlot[a_ == b_, xrange_List, yrange_List, opts___] := 
      Show[Graphics[
          ContourPlot[a - b, xrange, yrange, opts, 
		
            ContourStyle -> {Thickness[0.02], RGBColor[1, 0, 0]}]], 
        opts, AxesFront -> True, 
        DisplayFunction -> $DisplayFunction]; 


    equalcolorfunction[x_] := GrayLevel[1]; 


    InequalityPlot[a_ == b_, xrange_List, yrange_List, opts___] := 
      Show[Graphics[
          ContourPlot[a - b, xrange, yrange, opts, 
		
            ContourStyle -> {Thickness[0.02], RGBColor[1, 0, 0]}, 
		
            ColorFunction -> equalcolorfunction]], opts, 
        AxesFront -> True, DisplayFunction -> $DisplayFunction]; 

    
notequalcolorfunction[x_] := GrayLevel[.5]; 


    InequalityPlot[a_ ≠ b_, xrange_List, yrange_List, opts___] := 

      	Show[Graphics[
          ContourPlot[a - b, xrange, yrange, opts, 
		
            ColorFunction -> notequalcolorfunction, 
		
            ContourStyle -> {Thickness[0.02], GrayLevel[1]}]], opts, 
        AxesFront -> True, DisplayFunction -> $DisplayFunction]; 
    \)

Examples

InequalityPlot[x ≤ 2 y, {x, -3, 3}, {y, -3, 3}];

InequalityPlot[
      (x^2) ≤ -(y^2) + 25, {x, -10, 10}, {y, -10, 10}];

\(\(variations = 

      	{{InequalityPlot[
            x\^2 ≤ y\^2 - 20, {x, \(-10\), 10}, {y, \(-10\), 10}, 
            
				DisplayFunction -> Identity], 
			
          InequalityPlot[
            x\^2 < y\^2 - 20, {x, \(-10\), 10}, {y, \(-10\), 10}, 
				
            DisplayFunction -> Identity], 
			
          InequalityPlot[
            x\^2 > y\^2 - 20, {x, \(-10\), 10}, {y, \(-10\), 10}, 
				
            DisplayFunction -> Identity]}, 

        		{InequalityPlot[
            x\^2 ≥ y\^2 - 20, {x, \(-10\), 10}, {y, \(-10\), 
              10}, 
				DisplayFunction -> Identity], 
			
          InequalityPlot[
            x\^2 ≠ y\^2 - 20, {x, \(-10\), 10}, {y, \(-10\), 10}, 

            				DisplayFunction -> Identity], 
			
          InequalityPlot[
            x\^2 == y\^2 - 20, {x, \(-10\), 10}, {y, \(-10\), 10}, 
				
            DisplayFunction -> Identity]}}; \)\)

Show[GraphicsArray[variations]];

RiemannPlot

Code

Needs["Utilities`FilterOptions`"]

RiemannPlot::usage  =  
      "RiemannPlot[f, {x, xmin, xmax}] generates a plot of f as a function \
of x from xmin to xmax, with the area under the curve approximated by \
rectangles. ";

\(\(Options[RiemannPlot]\  = 

      	{Subdivisions\  -> \ 16, 
		ShowCurve\  -> \ True, 
		
          FillColor\  -> GrayLevel[0.7], Method -> Left, 
		
          BorderStyle -> \ GrayLevel[0]}~Join~Options[Plot]; \)\)

\(\(SetOptions[RiemannPlot, PlotRange -> All, 
	
      TextStyle 
        -> {FontFamily -> "Helvetica", 
          FontSlant -> "Oblique", FontSize -> 10}]; \)\)

\(Clear[RiemannPlot]; \ 
    RiemannPlot[func_, \ {var_, \ min_, \ max_}, 
	opts___?OptionQ]\  := 

      	Module[{rects, \ inc, \ subs, \ sc, fillc, outlines, n, meth, \ disp, 
          \ area = 0}, 

        		{subs, \ sc, fillc, \ outlines, meth, disp} = 
          \({Subdivisions, \ ShowCurve, FillColor, \ BorderStyle, Method, 
                DisplayFunction} /. Flatten[{opts}]\) /. 
            Options[RiemannPlot]; 
		inc\  = \ \((max\  - \ min)\)/subs; 

        \ \ \ \ \ \ \ 
        adj = Switch[meth, Left, 0, Right, inc, Midpoint, inc/2]; 
			
        rects\  = \ 
          Flatten[Table[
				
              \(\((area = area + #\ inc; {fillc, 
                      Rectangle[{n, 0}, {n + inc, #}], outlines, 
                      Line[{{n, 0}, {n + inc, 0}, {n + inc, #}, {n, #}, {n, 
                            0}}]})\)&\)[func /. var -> \((n + adj)\)], {
                n, min, max - \ inc, inc}]\ \ \ ]; 
		
				
        If[TrueQ[sc], 
			
          Show[{Graphics[rects], 
              Plot[func, \ {var, min, max}, DisplayFunction\  -> \ Identity, 
                Evaluate[
                  \(FilterOptions[Plot, \ ##]&\)\ @@\ 
                    Flatten[{opts, Options[RiemannPlot]}]]]}, 
				
            \(FilterOptions[Graphics, ##]&\)@@
              Flatten[{DisplayFunction\  -> \ disp, opts, 
					
                  PlotLabel\  -> \ 
                    "Approximate Area = "<>ToString[area]<>
                      "
 Calculated Area = "<>
                      ToString[NIntegrate[func, \ {var, \ min, \ max}]], 
                  Options[RiemannPlot]}]
			], 
				
          Show[Graphics[rects], 
            \(FilterOptions[Graphics, ##]&\)@@
              Flatten[{opts, 
							
                  PlotLabel\  -> \ 
                    "Approximate Area = "<>ToString[area]<>
                      "
 Calculated Area = "<>
                      ToString[NIntegrate[func, \ {var, \ min, \ max}]], 
                  Options[RiemannPlot]}]
				]
		]
]\)

Examples

Needs["Graphics`Master`"]

?RiemannPlot

Options[ RiemannPlot]

Method can be Midpoint, Left, or Right. It defaults to Left.

\(\(RiemannPlot[Sin[x]\/x, {x, 0.001, π}, 
	FillColor -> Red, 
	
      BorderStyle -> {Blue}, 
	PlotStyle -> {Thickness[0.01], Magenta}, 
	
      Method -> Right, 
	\ Subdivisions -> 40]; \)\)

Building Primitives

Using similar techniques we can easily build our own graphics primitives. As a simple example, we can create a function that returns an n-sided polygon.

\(poly[n_Integer] := 
	
      Polygon[Table[{Cos[\(i\ 2\ π\)\/n], \ Sin[\(i\ 2\ π\)\/n]}, {i, 
            1, n}]]\)

Show[ Graphics[ poly[5] ],  AspectRatio  -> Automatic ];

We can easily rewrite poly to accept the position of the center of the polygon.

\(poly[{x_, y_}, n_Integer] := 
	
      Polygon[Table[{Cos[\(i\ 2\ π\)\/n] + x, \ 
            Sin[\(i\ 2\ π\)\/n] + y}, {i, 1, n}]]\)

\(\(Show[\ 
      Graphics[\ 

        	{Hue[0], poly[{\(-1\), 1}, 3], Hue[0.5], \ poly[{2, 3}, 5]}\ ], \ 

      	AspectRatio\  -> Automatic\ ]; \)\)