Visualization and Graphics: Wolfram Mathematica Tutorial Collection

Download as pdf or txt
Download as pdf or txt
You are on page 1of 78

Wolfram Mathematica Tutorial Collection

Visualization and Graphics


For use with Wolfram Mathematica® 7.0 and later.

For the latest updates and corrections to this manual:


visit reference.wolfram.com
For information on additional copies of this documentation:
visit the Customer Service website at www.wolfram.com/services/customerservice
or email Customer Service at info@wolfram.com
Comments on this manual are welcomed at:
comments@wolfram.com

Printed in the United States of America.


15 14 13 12 11 10 9 8 7 6 5 4 3 2

©2008 Wolfram Research, Inc.


All rights reserved. No part of this document may be reproduced or transmitted, in any form or by any means,
electronic, mechanical, photocopying, recording or otherwise, without the prior written permission of the copyright
holder.
Wolfram Research is the holder of the copyright to the Wolfram Mathematica software system ("Software") described
in this document, including without limitation such aspects of the system as its code, structure, sequence,
organization, “look and feel,” programming language, and compilation of command names. Use of the Software
unless pursuant to the terms of a license granted by Wolfram Research or as otherwise authorized by law is an
infringement of the copyright.
Wolfram Research, Inc. and Wolfram Media, Inc. ("Wolfram") make no representations, express,
statutory, or implied, with respect to the Software (or any aspect thereof), including, without limitation,
any implied warranties of merchantability, interoperability, or fitness for a particular purpose, all of which
are expressly disclaimed. Wolfram does not warrant that the functions of the Software will meet your
requirements or that the operation of the Software will be uninterrupted or error free. As such, Wolfram
does not recommend the use of the software described in this document for applications in which errors
or omissions could threaten life, injury or significant loss.
Mathematica, MathLink, and MathSource are registered trademarks of Wolfram Research, Inc. J/Link, MathLM,
.NET/Link, and webMathematica are trademarks of Wolfram Research, Inc. Windows is a registered trademark of
Microsoft Corporation in the United States and other countries. Macintosh is a registered trademark of Apple
Computer, Inc. All other trademarks used herein are the property of their respective owners. Mathematica is not
associated with Mathematica Policy Research, Inc.
Contents

Graphics and Sound


Basic Plotting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Options for Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Redrawing and Combining Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Manipulating Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Three-Dimensional Surface Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Plotting Lists of Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Parametric Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Some Special Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
Sound . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31

The Structure of Graphics and Sound


The Structure of Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
Two-Dimensional Graphics Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Graphics Directives and Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Coordinate Systems for Two-Dimensional Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
Labeling Two-Dimensional Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
Insetting Objects in Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
Density and Contour Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
Three-Dimensional Graphics Primitives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
Three-Dimensional Graphics Directives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
Coordinate Systems for Three-Dimensional Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
Lighting and Surface Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
Labeling Three-Dimensional Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
Efficient Representation of Many Primitives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
Formats for Text in Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
Graphics Primitives for Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
The Representation of Sound . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
Exporting Graphics and Sounds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
Importing Graphics and Sounds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
Editing Mathematica Graphics
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
Drawing Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
Selecting Graphics Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
Reshaping Graphics Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
Resizing, Cropping, and Adding Margins to Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
Graphics as Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
Interacting with 3D Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
Graphics and Sound

Basic Plotting

Plot@ f ,8x,xmin ,xmax <D plot f as a function of x from xmin to xmax

Plot@ f ,8x,x0 ,x1 ,…,xk <D plot f over a series of segments, potentially breaking the
curve at each of the xi

Plot@8 f1 , f2 ,…<,8x,xmin ,xmax <D


plot several functions together

Basic plotting functions.

This plots a graph of sinHxL as a function of x from 0 to 2 p.


In[1]:= Plot@Sin@xD, 8x, 0, 2 Pi<D
1.0

0.5

Out[1]=
1 2 3 4 5 6

-0.5

-1.0

You can plot functions that have singularities. Mathematica will try to choose appropriate scales.
In[2]:= Plot@Tan@xD, 8x, - 3, 3<D
6
4
2
Out[2]=
-3 -2 -1 1 2 3
-2
-4
-6

The singularities can be omitted from the plot by specifying them in the plot's range.
In[3]:= Plot@Tan@xD, 8x, - 3, - Pi ê 2, Pi ê 2, 3<D
6
4
2
Out[3]=
-3 -2 -1 1 2 3
-2
-4
-6
2 Visualization and Graphics

You can give a list of functions to plot. A different color will automatically be used for each
function.
In[4]:= Plot@8Sin@xD, Sin@2 xD, Sin@3 xD<, 8x, 0, 2 Pi<D
1.0

0.5

Out[4]=
1 2 3 4 5 6

-0.5

-1.0

This finds the numerical solution to a differential equation, as discussed in "Numerical Differen-
tial Equations".
In[5]:= NDSolve@8y '@xD == Sin@y@xDD, y@0D == 1<, y, 8x, 0, 4<D
Out[5]= 88y Ø InterpolatingFunction@880., 4.<<, <>D<<

Here is a plot of the solution.


In[6]:= Plot@y@xD ê. %, 8x, 0, 4<D
3.0

2.5

Out[6]= 2.0

1.5

1 2 3 4

Options for Graphics


When Mathematica plots a graph for you, it has to make many choices. It has to work out what
the scales should be, where the function should be sampled, how the axes should be drawn,
and so on. Most of the time, Mathematica will probably make pretty good choices. However, if
you want to get the very best possible pictures for your particular purposes, you may have to
help Mathematica in making some of its choices.

There is a general mechanism for specifying “options” in Mathematica functions. Each option
has a definite name. As the last arguments to a function like Plot, you can include a sequence
of rules of the form name -> value, to specify the values for various options. Any option for which
you do not give an explicit rule is taken to have its “default” value.
Visualization and Graphics 3

Plot@ f ,8x,xmin ,xmax <,option->valueD


make a plot, specifying a particular value for an option

Choosing an option for a plot.

A function like Plot has many options that you can set. Usually you will need to use at most a
few of them at a time. If you want to optimize a particular plot, you will probably do best to
experiment, trying a sequence of different settings for various options.

Each time you produce a plot, you can specify options for it. "Redrawing and Combining Plots"
will also discuss how you can change some of the options, even after you have produced the
plot.

option name default value


AspectRatio 1ëGoldenRatio the height-to-width ratio for the plot;
Automatic sets it from the absolute x and
y coordinates
Axes True whether to include axes
AxesLabel None labels to be put on the axes; ylabel specifies
a label for the y axis, 8xlabel, ylabel< for
both axes
AxesOrigin Automatic the point at which axes cross
BaseStyle 8< the default style to use for the plot
TraditionalFoÖ the default format type to use for text in
FormatType
rm
the plot
Frame False whether to draw a frame around the plot
FrameLabel None labels to be put around the frame; give a
list in clockwise order starting with the
lower x axis
FrameTicks Automatic what tick marks to draw if there is a frame;
None gives no tick marks
GridLines None what grid lines to include; Automatic
includes a grid line for every major tick
mark
PlotLabel None an expression to be printed as a label for
the plot
PlotRange Automatic the range of coordinates to include in the
plot; All includes all points
Ticks Automatic what tick marks to draw if there are axes;
None gives no tick marks

Some of the options for Plot . These can also be used in Show .
4 Visualization and Graphics

Here is a plot with all options having their default values.


In[1]:= Plot@Sin@x ^ 2D, 8x, 0, 3<D
1.0

0.5

Out[1]=
0.5 1.0 1.5 2.0 2.5 3.0
-0.5

-1.0

This draws axes on a frame around the plot.


In[2]:= Plot@Sin@x ^ 2D, 8x, 0, 3<, Frame -> TrueD
1.0

0.5

Out[2]= 0.0

-0.5

-1.0
0.0 0.5 1.0 1.5 2.0 2.5 3.0

This specifies labels for the x and y axes. The expressions you give as labels are printed just as
they would be if they appeared as TraditionalForm Mathematica output. You can give any
piece of text by putting it inside a pair of double quotes.
In[3]:= Plot@Sin@x ^ 2D, 8x, 0, 3<, AxesLabel -> 8"x value", Sin@x ^ 2D<D
sinIx2 M
1.0

0.5
Out[3]=
x value
0.5 1.0 1.5 2.0 2.5 3.0
-0.5

-1.0

You can give several options at the same time, in any order.
In[4]:= Plot@Sin@x ^ 2D, 8x, 0, 3<, Frame -> True, GridLines -> AutomaticD
1.0

0.5

Out[4]= 0.0

-0.5

-1.0
0.0 0.5 1.0 1.5 2.0 2.5 3.0
Visualization and Graphics 5

Setting the AspectRatio option changes the whole shape of your plot. AspectRatio gives
the ratio of width to height. Its default value is the inverse of the Golden Ratio~supposedly the
most pleasing shape for a rectangle.
In[5]:= Plot@Sin@x ^ 2D, 8x, 0, 3<, AspectRatio -> 1D
1.0

0.5

Out[5]=
0.5 1.0 1.5 2.0 2.5 3.0

-0.5

-1.0

Automatic use internal algorithms

None do not include this

All include everything

True do this

False do not do this

Some common settings for various options.

When Mathematica makes a plot, it tries to set the x and y scales to include only the
“interesting” parts of the plot. If your function increases very rapidly, or has singularities, the
parts where it gets too large will be cut off. By specifying the option PlotRange, you can control
exactly what ranges of x and y coordinates are included in your plot.

Automatic show at least a large fraction of the points, including the


“interesting” region (the default setting)
All show all points
8ymin ,ymax < show a specific range of y values
8xrange,yrange< show the specified ranges of x and y values

Settings for the option PlotRange.


6 Visualization and Graphics

The setting for the option PlotRange gives explicit y limits for the graph. With the y limits
specified here, the bottom of the curve is cut off.
In[6]:= Plot@Sin@x ^ 2D, 8x, 0, 3<, PlotRange -> 80, 1.2<D
1.2
1.0
0.8

Out[6]= 0.6
0.4
0.2

0.5 1.0 1.5 2.0 2.5 3.0

Mathematica always tries to plot functions as smooth curves. As a result, in places where your
function wiggles a lot, Mathematica will use more points. In general, Mathematica tries to adapt
its sampling of your function to the form of the function. There is, however, a limit, which you
can set, to how finely Mathematica will ever sample a function.

1
The function sin J N wiggles infinitely often when x > 0. Mathematica tries to sample more points
x
in the region where the function wiggles a lot, but it can never sample the infinite number that
you would need to reproduce the function exactly. As a result, there are slight glitches in the
plot.
In[7]:= Plot@Sin@1 ê xD, 8x, - 1, 1<D
1.0

0.5

Out[7]=
-1.0 -0.5 0.5 1.0

-0.5

-1.0

It is important to realize that since Mathematica can only sample your function at a limited
number of points, it can always miss features of the function. Mathematica adaptively samples
the functions, increasing the number of samples near interesting features, but it is still possible
to miss something. By increasing PlotPoints, you can make Mathematica sample your function
at a larger number of points. Of course, the larger you set PlotPoints to be, the longer it will
take Mathematica to plot any function, even a smooth one.

option name default value


PlotStyle Automatic a list of lists of graphics primitives to use
for each curve (see "Graphics Directives
and Options")
ClippingStyle None what to draw when curves are clipped
Visualization and Graphics 7

Filling None filling to insert under each curve


FillingStyle Automatic style to use for filling
PlotPoints 50 the initial number of points at which to
sample the function
MaxRecursion Automatic the maximum number of recursive subdivi -
sions allowed

More options for Plot . These cannot be used in Show .

This uses PlotStyle to specify a dashed curve.


In[8]:= Plot@Sin@x ^ 2D, 8x, 0, 3<, PlotStyle Ø DashedD
1.0

0.5

Out[8]=
0.5 1.0 1.5 2.0 2.5 3.0

-0.5

-1.0

When plotting multiple functions, PlotStyle settings in a list are used sequentially for each
function.
In[9]:= Plot@8Sin@x ^ 2D, Cos@x ^ 2D<, 8x, 0, 3<, PlotStyle Ø 8Red, Blue<D
1.0

0.5

Out[9]=
0.5 1.0 1.5 2.0 2.5 3.0

-0.5

-1.0

When a PlotStyle contains a sublist, the settings are combined.


In[10]:= Plot@8Sin@x ^ 2D, Cos@x ^ 2D<, 8x, 0, 3<, PlotStyle Ø 8Red, 8Blue, Thick<<D
1.0

0.5

Out[10]=
0.5 1.0 1.5 2.0 2.5 3.0

-0.5

-1.0
8 Visualization and Graphics

By default nothing is indicated when the PlotRange is set, so that it cuts off curves.
In[11]:= Plot@8Sin@x ^ 2D, Cos@x ^ 2D<, 8x, 0, 3<, PlotRange Ø 0.9D

0.5

Out[11]=
0.5 1.0 1.5 2.0 2.5 3.0

-0.5

Setting ClippingStyle to Automatic draws a dashed line where a curve is cut off.
In[12]:= Plot@8Sin@x ^ 2D, Cos@x ^ 2D<, 8x, 0, 3<, PlotRange Ø 0.9, ClippingStyle Ø AutomaticD

0.5

Out[12]=
0.5 1.0 1.5 2.0 2.5 3.0

-0.5

Setting ClippingStyle to a list defines the style for the parts cut off at the bottom and top.
In[13]:= Plot@8Sin@x ^ 2D, Cos@x ^ 2D<, 8x, 0, 3<,
PlotRange Ø 0.9, ClippingStyle Ø 8Green, Red<D

0.5

Out[13]=
0.5 1.0 1.5 2.0 2.5 3.0

-0.5

This specifies filling between the curve and the x axis.


In[14]:= Plot@Sin@x ^ 2D, 8x, 0, 3<, Filling Ø AxisD

Out[14]=
Visualization and Graphics 9

The filling can be specified to extend to an arbitrary height, such as the bottom of the graphic.
Filling colors are automatically blended where they overlap.
In[15]:= Plot@8Sin@xD, Cos@xD<, 8x, 0, 3<, Filling Ø BottomD

Out[15]=

This specifies a specific filling to be used only for the first curve.
In[16]:= Plot@8Sin@xD, Cos@xD<, 8x, 0, 3<, Filling Ø 81 Ø .5<D

Out[16]=

This shows a filling from the first curve to the second using a nondefault filling style.
In[17]:= Plot@8Sin@xD, Cos@xD<, 8x, 0, 3<, Filling Ø 81 Ø 82<<, FillingStyle Ø LightBrownD
1.0

0.5

Out[17]=
0.5 1.0 1.5 2.0 2.5 3.0

-0.5

-1.0

Redrawing and Combining Plots


Mathematica saves information about every plot you produce, so that you can later redraw it.
When you redraw plots, you can change some of the options you use.

Show@plot,option->valueD redraw a plot with options changed


Show@plot1 ,plot2 ,…D combine several plots
GraphicsGrid@88plot1 ,plot2 ,…<,…<D
draw an array of plots
InputForm@plotD show the underlying textual description of the plot

Functions for manipulating plots.


10 Visualization and Graphics

Here is a simple plot.


In[1]:= Plot@ChebyshevT@7, xD, 8x, - 1, 1<D
1.0

0.5

Out[1]=
-1.0 -0.5 0.5 1.0

-0.5

-1.0

When you redraw the plot, you can change some of the options. This changes the choice of y
scale.
In[2]:= Show@%, PlotRange -> 8- 1, 2<D
2.0

1.5

1.0
Out[2]= 0.5

-1.0 -0.5 0.5 1.0


-0.5

-1.0

This takes the plot from the previous line, and changes another option in it.
In[3]:= Show@%, PlotLabel -> "A Chebyshev Polynomial"D
A Chebyshev Polynomial
2.0

1.5

1.0
Out[3]=
0.5

-1.0 -0.5 0.5 1.0


-0.5

-1.0

By using Show with a sequence of different options, you can look at the same plot in many
different ways. You may want to do this, for example, if you are trying to find the best possible
setting of options.

You can also use Show to combine plots. All of the options for the resulting graphic will be based
upon the options of the first graphic in the Show expression.
Visualization and Graphics 11

This sets gj0 to be a plot of J0 HxL from x = 0 to 10.


In[4]:= gj0 = Plot@BesselJ@0, xD, 8x, 0, 10<D
1.0
0.8
0.6
0.4
Out[4]=
0.2

2 4 6 8 10
-0.2
-0.4

Here is a plot of Y1 HxL from x = 1 to 10.


In[5]:= gy1 = Plot@BesselY@1, xD, 8x, 1, 10<D
0.4

0.2

4 6 8 10
Out[5]= -0.2

-0.4

-0.6

-0.8

Plot specifies an explicit PlotRange for each graphic.


In[6]:= Options@gj0, PlotRangeD
Out[6]= 8PlotRange Ø 880, 10<, 8-0.402759, 1.<<<

This uses PlotRange to override the explicit value set for gj0.
In[7]:= gjy = Show@gj0, gy1, PlotRange Ø AutomaticD
1.0

0.5

Out[7]=
2 4 6 8 10

-0.5

All Mathematica graphics are expressions and can be manipulated in the same way as any other
expression. Doing these kinds of manipulations does not require the use of Show.
12 Visualization and Graphics

This replaces all instances of the symbol Line with the symbol Point in the graphics expres-
sion represented by gj0.
In[8]:= gj0 ê. Line Ø Point
1.0
0.8
0.6
0.4
Out[8]=
0.2

2 4 6 8 10
-0.2
-0.4

Using Show@plot1 , plot2 , …D you can combine several plots into one. GraphicsGrid allows you
to draw several plots in an array.

GraphicsGrid@88plot11 ,plot12 ,…<,…<D


draw a rectangular array of plots
GraphicsRow @8plot1 ,plot2 ,…<D
draw several plots side by side
GraphicsColumn@8plot1 ,plot2 ,…<D
draw a column of plots
GraphicsGridAplots,Spacings->8h,v<E
put the specified horizontal and vertical spacing between
the plots

Drawing arrays of plots.

This shows the previous plots in an array.


In[9]:= GraphicsGrid@88gj0, gjy<, 8gy1, gjy<<D
1.0 1.0
0.8
0.6 0.5
0.4
0.2
2 4 6 8 10
-0.2 2 4 6 8 10 -0.5
-0.4
Out[9]=
0.4
1.0
0.2
0.5
4 6 8 10
-0.2
-0.4 2 4 6 8 10
-0.6 -0.5
-0.8
Visualization and Graphics 13

If you redisplay an array of plots using Show , any options you specify will be used for the whole
array, rather than for individual plots.
In[10]:= Show@%, Frame -> True, FrameTicks -> NoneD
1.0 1.0
0.8
0.6 0.5
0.4
0.2
2 4 6 8 10
-0.2 2 4 6 8 10 -0.5
-0.4
Out[10]=
0.4
1.0
0.2
0.5
4 6 8 10
-0.2
-0.4 2 4 6 8 10
-0.6 -0.5
-0.8

GraphicsGrid by default puts a narrow border around each of the plots in the array it gives.
You can change the size of this border by setting the option Spacings -> 8h, v<. The parame-
ters h and v give the horizontal and vertical spacings to be used. The Spacings option uses the
width and height of characters in the default font to scale the h and v parameters by default,
but it is generally more useful in graphics to use Scaled coordinates. Scaled scales widths and
heights so that a value of 1 represents the width and height of one element of the grid.

This increases the horizontal spacing, but decreases the vertical spacing between the plots in
the array.
In[11]:= GraphicsGrid@88gj0, gjy<, 8gy1, gjy<<, Spacings -> 8Scaled@.3D, Scaled@0D<D
1.0 1.0
0.8
0.6 0.5
0.4
0.2
2 4 6 8 10
-0.2 2 4 6 8 10 -0.5
-0.4
Out[11]= 0.4
1.0
0.2
0.5
4 6 8 10
-0.2
-0.4 2 4 6 8 10
-0.6 -0.5
-0.8

When you make a plot, Mathematica saves the list of points it used, together with some other
information. Using what is saved, you can redraw plots in many different ways with Show.
However, you should realize that no matter what options you specify, Show still has the same
basic set of points to work with. So, for example, if you set the options so that Mathematica
displays a small portion of your original plot magnified, you will probably be able to see the
individual sample points that Plot used. Options like PlotPoints can only be set in the original
Plot command itself. (Mathematica always plots the actual points it has; it avoids using
smoothed or splined curves, which can give misleading results in mathematical graphics.)

Here is a simple plot.


14 Visualization and Graphics

Here is a simple plot.


In[12]:= Plot@Cos@xD, 8x, - Pi, Pi<D
1.0

0.5

Out[12]=
-3 -2 -1 1 2 3

-0.5

-1.0

This shows a small region of the plot in a magnified form. At this resolution, you can see the
individual line segments that were produced by the original Plot command.
In[13]:= Show@%, PlotRange -> 880, .005<, 8.99999, 1<<D
1.000000

0.999998

0.999996
Out[13]=
0.999994

0.999992

0.999990

Manipulating Options
There are a number of functions built into Mathematica which, like Plot, have various options
you can set. Mathematica provides some general mechanisms for handling such options.

If you do not give a specific setting for an option to a function like Plot, then Mathematica will
automatically use a default value for the option. The function Options@ function, optionD allows
you to find out the default value for a particular option. You can reset the default using
SetOptions@ function, option -> valueD. Note that if you do this, the default value you have given
will stay until you explicitly change it.

Options@ functionD give a list of the current default settings for all options
Options@ function,optionD give the default setting for a particular option
SetOptions@ function,option->value,…D
reset defaults

Manipulating default settings for options.


Visualization and Graphics 15

Here is the default setting for the PlotRange option of Plot .


In[1]:= Options@Plot, PlotRangeD
Out[1]= 8PlotRange Ø 8Full, Automatic<<

This resets the default for the PlotRange option. The semicolon stops Mathematica from
printing out the rather long list of options for Plot .
In[2]:= SetOptions@Plot, PlotRange -> AllD;

Until you explicitly reset it, the default for the PlotRange option will now be All.
In[3]:= Options@Plot, PlotRangeD
Out[3]= 8PlotRange Ø All<

The graphics objects that you get from Plot or Show store information on the options they use.
You can get this information by applying the Options function to these graphics objects.

Options@plotD show all the options used for a particular plot


Options@plot,optionD show the setting for a specific option
AbsoluteOptions@plot,optionD show the absolute form used for a specific option, even if
the setting for the option is Automatic or All

Getting information on options used in plots.

Here is a plot, with default settings for all options.


In[4]:= g = Plot@SinIntegral@xD, 8x, 0, 20<D

1.5

1.0
Out[4]=

0.5

5 10 15 20

The setting used for the PlotRange option was All.


In[5]:= Options@g, PlotRangeD
Out[5]= 8PlotRange Ø 8All, All<<

AbsoluteOptions gives the absolute automatically chosen values used for PlotRange.
In[6]:= AbsoluteOptions@g, PlotRangeD
-7 -7
Out[6]= 9PlotRange Ø 994.08163 µ 10 , 20.=, 94.08163 µ 10 , 1.85194===
16 Visualization and Graphics

While it is often convenient to use a variable to represent a graphic as in the above examples,
the graphic itself can be evaluated directly. The typical ways to do this in the notebook interface
are to copy and paste the graphic or to simply begin typing in the graphical output cell, at
which point the output cell will be converted into a new input cell.

When a plot created with no explicit ImageSize is placed into an input cell, it will automatically
shrink to more easily accommodate input.

The following input cell was created by copying and pasting the graphical output created in the
previous example.

1.5

1.0
In[7]:= AbsoluteOptionsB , PlotRangeF
0.5

5 10 15 20
-7 -7
Out[7]= 9PlotRange Ø 994.08163 µ 10 , 20.=, 94.08163 µ 10 , 1.85194===

Three-Dimensional Surface Plots

Plot3D@ f ,8x,xmin ,xmax <,8y,ymin ,ymax <D


make a three-dimensional plot of f as a function of the
variables x and y

Basic 3D plotting function.

This makes a three-dimensional plot of the function sinHxyL.


In[1]:= Plot3D@Sin@x yD, 8x, 0, 3<, 8y, 0, 3<D

Out[1]=
Visualization and Graphics 17

Three-dimensional graphics can be rotated in place by dragging the mouse inside of the
graphic. Dragging inside of the graphic causes the graphic to tumble in a direction that follows
the mouse, and dragging around the borders of the graphic causes the graphic to spin in the
plane of the screen. Dragging the graphic while holding down the Shift key causes the graphic
to pan. Use the Ctrl key (Cmd key on Macintosh) to zoom.

There are many options for three-dimensional plots in Mathematica. Some are discussed here;
others are described in "The Structure of Graphics and Sound".

The first set of options for three-dimensional plots is largely analogous to those provided in the
two-dimensional case.

option name default value


Axes True whether to include axes
AxesLabel None labels to be put on the axes: zlabel specifies
a label for the z axis,
8xlabel, ylabel, zlabel< for all axes
BaseStyle 8< the default style to use for the plot
Boxed True whether to draw a three-dimensional box
around the surface
FaceGrids None how to draw grids on faces of the bounding
box; All draws a grid on every face
LabelStyle 8< style specification for labels
Lighting Automatic simulated light sources to use
Mesh Automatic whether an xy mesh should be drawn on
the surface
PlotRange 9Full,Full, the range of z or other values to include
Automatic=
SphericalRegion False whether to make the circumscribing sphere
fit in the final display area
ViewAngle All angle of the field of view
ViewCenter 81,1,1<ê2 point to display at the center
ViewPoint 81.3,-2.4,2< the point in space from which to look at the
surface
ViewVector Automatic position and direction of a simulated camera
ViewVertical 80,0,1< direction to make vertical
BoundaryStyle Automatic how to draw boundary lines for surfaces
ClippingStyle Automatic how to draw clipped parts of surfaces
ColorFunction Automatic how to determine the color of the surfaces
Filling None filling under each surface
18 Visualization and Graphics

FillingStyle Opacity@.5D style to use for filling


PlotPoints 25 the number of points in each direction at
which to sample the function; 9nx , ny =
specifies different numbers in the x and y
directions
PlotStyle Automatic graphics directives for the style of each
surface

Some options for Plot3D. The first set can also be used in Show .

This redraws the previous plot with options changed. With this setting for PlotRange, only the
part of the surface in the range -0.5 § z § 0.5 is shown.
In[2]:= Show@%, PlotRange -> 8- 0.5, 0.5<D

Out[2]=

The ClippingStyle option of Plot3D can be used to fill in the clipped regions.
In[3]:= Plot3D@Sin@x yD, 8x, 0, 3<, 8y, 0, 3<,
PlotRange -> 8- 0.5, 0.5<, ClippingStyle Ø 8Opacity@.9, GrayD<D

Out[3]=

When you make the original plot, you can choose to sample more points. Mathematica adap-
tively samples the plot, adding points for large variations, but occasionally you may still need to
specify a greater number of points.
In[4]:= Plot3D@10 Sin@x + Sin@yDD, 8x, - 10, 10<, 8y, - 10, 10<, PlotPoints -> 50D

Out[4]=
Visualization and Graphics 19

Here is the same plot, with labels for the axes, and grids added to each face.
In[5]:= Show@%, AxesLabel -> 8"Time", "Depth", "Value"<, FaceGrids -> AllD

Out[5]=

Probably the single most important issue in plotting a three-dimensional surface is specifying
where you want to look at the surface from. The ViewPoint option for Plot3D and Show allows
you to specify the point 8x, y, z< in space from which you view a surface. The details of how the
coordinates for this point are defined are discussed in "Coordinate Systems for Three-Dimen-
sional Graphics". When rotating a graphic using the mouse, you are adjusting the ViewPoint
value.

Here is a surface, viewed from the default view point 81.3, - 2.4, 2<. This view point is
chosen to be “generic”, so that visually confusing coincidental alignments between different
parts of your object are unlikely.
In[6]:= Plot3D@Sin@x yD, 8x, 0, 3<, 8y, 0, 3<D

Out[6]=

This redraws the picture, with the view point directly in front. Notice the perspective effect that
makes the back of the box look much smaller than the front.
In[7]:= Show@%, ViewPoint -> 80, - 2, 0<D

Out[7]=
20 Visualization and Graphics

The ViewPoint option also accepts various symbolic values which represent common view
points.
In[8]:= Show@%, ViewPoint Ø AboveD

Out[8]=

81.3,-2.4,2< default view point


Front in front, along the negative y direction

Back in back, along the positive y direction


Above above, along the positive z direction
Below below, along the negative z direction
Left left, along the negative x direction

Right right, along the positive x direction

Typical choices for the ViewPoint option.

The human visual system is not particularly good at understanding complicated mathematical
surfaces. As a result, you need to generate pictures that contain as many clues as possible
about the form of the surface.

View points slightly above the surface usually work best. It is generally a good idea to keep the
view point close enough to the surface that there is some perspective effect. Having a box
explicitly drawn around the surface is helpful in recognizing the orientation of the surface.
Visualization and Graphics 21

Here is a plot with the default settings for surface rendering options.
In[9]:= Plot3D@Exp@- Hx ^ 2 + y ^ 2LD, 8x, - 2, 2<, 8y, - 2, 2<D

Out[9]=

This shows the surface without the mesh drawn. It is usually much harder to see the form of
the surface if the mesh is not there.
In[10]:= Plot3D@Exp@- Hx ^ 2 + y ^ 2LD, 8x, - 2, 2<, 8y, - 2, 2<, Mesh Ø NoneD

Out[10]=

To add an extra element of realism to three-dimensional graphics, Mathematica by default


colors three-dimensional surfaces using a simulated lighting model. In the default case, Mathe-
matica assumes that there are four point light sources plus ambient lighting shining on the
object. "Lighting and Surface Properties" describes how you can set up other light sources, and
how you can specify the reflection properties of an object.

Lighting can also be specified using a string which represents a collection of lighting properties.
For example, the option setting Lighting -> "Neutral" uses a set of white lights, and so can
be faithfully reproduced on a black and white output device such as a printer.

In[11]:= Plot3D@8Sin@x yD<, 8x, 0, 3<, 8y, 0, 3<, Lighting Ø "Neutral"D

Out[11]=
22 Visualization and Graphics

The ColorFunction option by default uses Lighting -> "Neutral" so that the surface
colors are not distorted by colored lights.
In[12]:= Plot3D@8Sin@x yD<, 8x, 0, 3<, 8y, 0, 3<, ColorFunction Ø HueD

Out[12]=

Plotting Lists of Data


Mathematica can be used to make plots of functions. You give Mathematica a function, and it
builds up a curve or surface by evaluating the function at many different points.

Here we describe how you can make plots from lists of data, instead of functions. ("Importing
and Exporting Data" discusses how to read data from external files and programs.) The Mathe-
matica commands for plotting lists of data are direct analogs of the ones for plotting functions.

ListPlot@8y1 ,y2 ,…<D plot y1 , y2 , … at x values 1, 2, …


ListPlot@88x1 ,y1 <,8x2 ,y2 <,…<E plot points Hx1 , y1 L, …

ListLinePlot@listD join the points with lines


ListPlot3D@88z11 ,z12 ,…<,8z21 ,z22 ,…<,…<D
make a three-dimensional plot of the array of heights zyx

ListPlot3D@88x1 ,y1 ,z1 <,8x2 ,y2 ,z2 <,…<D


make a three-dimensional plot with heights zi at positions
8xi , yi <
ListContourPlot@arrayD make a contour plot
ListDensityPlot@arrayD make a density plot

Functions for plotting lists of data.

Here is a list of values.


In[1]:= t = Table@i ^ 2, 8i, 10<D
Out[1]= 81, 4, 9, 16, 25, 36, 49, 64, 81, 100<
Visualization and Graphics 23

This plots the values.


In[2]:= ListPlot@tD
100

80

60
Out[2]=
40

20

2 4 6 8 10

This joins the points with lines.


In[3]:= ListLinePlot@tD
100

80

60
Out[3]=
40

20

2 4 6 8 10

When plotting multiple datasets, Mathematica chooses a different color for each dataset
automatically.
In[4]:= ListPlot@8t, 2 t<D
200

150

Out[4]= 100

50

2 4 6 8 10

This gives a list of x, y pairs.


In[5]:= Table@8i ^ 2, 4 i ^ 2 + i ^ 3<, 8i, 10<D
Out[5]= 881, 5<, 84, 24<, 89, 63<, 816, 128<, 825, 225<,
836, 360<, 849, 539<, 864, 768<, 881, 1053<, 8100, 1400<<
24 Visualization and Graphics

This plots the points.


In[6]:= ListPlot@%D
1400
1200
1000
800
Out[6]=
600
400
200

20 40 60 80 100

This gives a rectangular array of values. The array is quite large, so we end the input with a
semicolon to stop the result from being printed out.
In[7]:= t3 = Table@Mod@x, yD, 8x, 30<, 8y, 20<D;

This makes a three-dimensional plot of the array of values.


In[8]:= ListPlot3D@t3D

Out[8]=

This gives a density plot of the array of values.


In[9]:= ListDensityPlot@t3D

Out[9]=
Visualization and Graphics 25

Parametric Plots
"Basic Plotting" described how to plot curves in Mathematica in which you give the y coordinate
of each point as a function of the x coordinate. You can also use Mathematica to make paramet-
ric plots. In a parametric plot, you give both the x and y coordinates of each point as a function
of a third parameter, say t.

ParametricPlotA9 fx , fy =,9t,tmin ,tmax =E


make a parametric plot
ParametricPlotA99 fx , fy =,9gx ,gy =,…=,9t,tmin ,tmax =E
plot several parametric curves together

Functions for generating parametric plots.

Here is the curve made by taking the x coordinate of each point to be Sin@tD and the y coordi-
nate to be Sin@2 tD.
In[1]:= ParametricPlot@8Sin@tD, Sin@2 tD<, 8t, 0, 2 Pi<D
1.0

0.5

Out[1]=
-1.0 -0.5 0.5 1.0

-0.5

-1.0

ParametricPlot3DA9 fx , fy , fz =,9t,tmin ,tmax =E


make a parametric plot of a three-dimensional curve
ParametricPlot3DA9 fx , fy , fz =,9t,tmin ,tmax =,9u,umin ,umax =E
make a parametric plot of a three-dimensional surface
ParametricPlot3DA99 fx , fy , fz =,9gx ,gy ,gz =,…=,…E
plot several objects together

Three-dimensional parametric plots.


26 Visualization and Graphics

ParametricPlot3D@8 fx , fy , fz <, 8t, tmin , tmax <D is the direct analog in three dimensions of

ParametricPlotA9 fx , fy =, 8t, tmin , tmax <E in two dimensions. In both cases, Mathematica effec-

tively generates a sequence of points by varying the parameter t, then forms a curve by joining
these points. With ParametricPlot, the curve is in two dimensions; with ParametricPlot3D, it
is in three dimensions.

This makes a parametric plot of a helical curve. Varying t produces circular motion in the x-y
plane, and linear motion in the z direction.
In[2]:= ParametricPlot3D@8Sin@tD, Cos@tD, t ê 3<, 8t, 0, 15<D
1.0
1.0 0.5
0.0
0.5 0.5
0.0 1.0
0.5
1.0

Out[2]=

ParametricPlot3D@8 fx , fy , fz <, 8t, tmin , tmax <, 8u, umin , umax <D creates a surface, rather than a

curve. The surface is formed from a collection of quadrilaterals. The corners of the quadrilater-
als have coordinates corresponding to the values of the fi when t and u take on values in a
regular grid.

Here the x and y coordinates for the quadrilaterals are given simply by t and u. The result is a
surface plot of the kind that can be produced by Plot3D.
In[3]:= ParametricPlot3D@8u Sin@tD, u Cos@tD, u<, 8t, 0, 2 Pi<, 8u, - 1, 1<D

Out[3]=
Visualization and Graphics 27

This shows the same surface as before, but with the y coordinates distorted by a quadratic
transformation.
In[4]:= ParametricPlot3D@8u Sin@tD, u ^ 2 Cos@tD, u<, 8t, 0, 2 Pi<, 8u, - 1, 1<D

Out[4]=

This produces a helicoid surface by taking the helical curve shown above, and at each section of
the curve drawing a quadrilateral.
In[5]:= ParametricPlot3D@8u Sin@tD, u Cos@tD, t ê 3<, 8t, 0, 15<, 8u, - 1, 1<D

Out[5]=

In general, it is possible to construct many complicated surfaces using ParametricPlot3D. In


each case, you can think of the surfaces as being formed by “distorting” or “rolling up” the t-u
coordinate grid in a certain way.
28 Visualization and Graphics

This produces a cylinder. Varying the t parameter yields a circle in the x-y plane, while varying
u moves the circles in the z direction.
In[6]:= ParametricPlot3D@8Sin@tD, Cos@tD, u<, 8t, 0, 2 Pi<, 8u, 0, 2<D

Out[6]=

This produces a torus. Varying u yields a circle, while varying t rotates the circle around the z
axis to form the torus.
In[7]:= ParametricPlot3D@
8Cos@tD H3 + Cos@uDL, Sin@tD H3 + Cos@uDL, Sin@uD<, 8t, 0, 2 Pi<, 8u, 0, 2 Pi<D

Out[7]=

This produces a sphere.


In[8]:= ParametricPlot3D@8Cos@tD Cos@uD, Sin@tD Cos@uD, Sin@uD<,
8t, 0, 2 Pi<, 8u, - Pi ê 2, Pi ê 2<D

Out[8]=

You should realize that when you draw surfaces with ParametricPlot3D, the exact choice of
parametrization is often crucial. You should be careful, for example, to avoid parametrizations
Visualization and Graphics 29

in which all or part of your surface is covered more than once. Such multiple coverings often
lead to discontinuities in the mesh drawn on the surface, and may make ParametricPlot3D
take much longer to render the surface.

Some Special Plots


As discussed in "The Structure of Graphics and Sound", Mathematica includes a full graphics
programming language. In this language, you can set up many different kinds of plots. A few of
the common ones are included in standard Mathematica packages.

LogPlot@ f ,8x,xmin ,xmax <D generate a linear-log plot


LogLinearPlot@ f ,8x,xmin ,xmax <D generate a log-linear plot
LogLogPlot@ f ,8x,xmin ,xmax <D generate a log-log plot
ListLogPlot @listD generate a linear-log plot from a list of data
ListLogLinearPlot@listD generate a log-linear plot from a list of data
ListLogLogPlot@listD generate a log-log plot from a list of data
PolarPlot@r,8t,tmin ,tmax <D generate a polar plot of the radius r as a function of angle t
SphericalPlot3D@r,8theta,min,max<,8phi,min,max<D
generate a three-dimensional spherical plot
BarChart@listD plot a list of data as a bar chart
ErrorListPlot@88x1 ,y1 ,dy1 <,…<D generate a plot with error bars
PieChart@listD plot a list of data as a pie chart

Some special plotting functions. The second group of functions are defined in standard Mathematica
packages.

This generates a log-linear plot.


In[1]:= LogPlot@Exp@- xD + 4 Exp@- 2 xD, 8x, 0, 6<D

Out[1]= 0.1

0.01

1 2 3 4 5 6
30 Visualization and Graphics

Here is a list of the first 10 primes.


In[2]:= p = Table@Prime@nD, 8n, 10<D
Out[2]= 82, 3, 5, 7, 11, 13, 17, 19, 23, 29<

Here is a bar chart of the primes.


In[3]:= Needs@"BarCharts`"D

In[4]:= BarChart@pD

Out[4]=

This gives a pie chart.


In[5]:= Needs@"PieCharts`"D

In[6]:= PieChart@pD

6
5

7
4

2
1
Out[6]=
8

10

9
Visualization and Graphics 31

Sound
On most computer systems, Mathematica can produce not only graphics but also sound. Mathe-
matica treats graphics and sound in a closely analogous way.

For example, just as you can use Plot@ f , 8x, xmin , xmax <D to plot a function, so also you can use
Play@ f , 8t, 0, tmax <D to “play” a function. Play takes the function to define the waveform for a
sound: the values of the function give the amplitude of the sound as a function of time.

Play@ f ,8t,0,tmax <D play a sound with amplitude f as a function of time t in


seconds

Playing a function.

On a suitable computer system, this plays a pure tone with a frequency of 440 hertz for one
second.
In[1]:= Play@Sin@2 Pi 440 tD, 8t, 0, 1<D

Out[1]=

Sounds produced by Play can have any waveform. They do not, for example, have to consist of
a collection of harmonic pieces. In general, the amplitude function you give to Play specifies
the instantaneous signal associated with the sound. This signal is typically converted to a volt-
age, and ultimately to a displacement. Note that amplitude is sometimes defined to be the peak
signal associated with a sound; in Mathematica, it is always the instantaneous signal as a
function of time.

This plays a more complex sound.


In[2]:= Play@Sin@700 t + 25 t Sin@350 tDD, 8t, 0, 4<D

Out[2]=
32 Visualization and Graphics

Play is set up so that the time variable that appears in it is always measured in absolute sec-
onds. When a sound is actually played, its amplitude is sampled a certain number of times
every second. You can specify the sample rate by setting the option SampleRate.

PlayA f ,9t,0,tmax =,SampleRate->rE


play a sound, sampling it r times a second

Specifying the sample rate for a sound.

In general, the higher the sample rate, the better high-frequency components in the sound will
be rendered. A sample rate of r typically allows frequencies up to r ê 2 hertz. The human auditory
system can typically perceive sounds in the frequency range 20 to 22000 hertz (depending
somewhat on age and sex). The fundamental frequencies for the 88 notes on a piano range
from 27.5 to 4096 hertz.

The standard sample rate used for compact disc players is 44100. The effective sample rate in
a typical telephone system is around 8000. On most computer systems, the default sample rate
used by Mathematica is around 8000.

You can use Play@8 f1 , f2 , …D to produce stereo sound. In general, Mathematica supports any
number of sound channels.

ListPlayA8a1 ,a2 ,…<,SampleRate->rE


play a sound with a sequence of amplitude levels

Playing sampled sounds.

The function ListPlay allows you simply to give a list of values which are taken to be sound
amplitudes sampled at a certain rate.

When sounds are actually rendered by Mathematica, only a certain range of amplitudes is
allowed. The option PlayRange in Play and ListPlay specifies how the amplitudes you give
should be scaled to fit in the allowed range. The settings for this option are analogous to those
for the PlotRange graphics option discussed in "Options for Graphics".
Visualization and Graphics 33

PlayRange->Automatic use an internal procedure to scale amplitudes


PlayRange->All scale so that all amplitudes fit in the allowed range
PlayRange->8amin ,amax < make amplitudes between amin and amax fit in the allowed
range, and clip others

Specifying the scaling of sound amplitudes.

While it is often convenient to use the setting PlayRange -> Automatic, you should realize that
Play may run significantly faster if you give an explicit PlayRange specification, so it does not
have to derive one.

EmitSound@sndD emit a sound when evaluated

Playing sounds programmatically.

A Sound object in output is typically formatted as a button which contains a visualization of the
sound and which plays the sound when pressed. Sounds can be played without the need for
user intervention or producing output by using EmitSound. In fact, the internal implementation
of Sound buttons uses EmitSound when the button is pressed.

The internal structure of Sound objects is discussed in "The Representation of Sound".

The Structure of Graphics and Sound

The Structure of Graphics


"Graphics and Sound" discusses how to use functions like Plot and ListPlot to plot graphs of
functions and data. Here, we discuss how Mathematica represents such graphics, and how you
can program Mathematica to create more complicated images.

The basic idea is that Mathematica represents all graphics in terms of a collection of graphics
primitives. The primitives are objects like Point, Line and Polygon, that represent elements of
a graphical image, as well as directives such as RGBColor and Thickness.
34 Visualization and Graphics

This generates a plot of a list of points.


In[1]:= ListPlot@Table@Prime@nD, 8n, 20<DD
70

60

50

40
Out[1]=
30

20

10

5 10 15 20

InputForm shows how Mathematica represents the graphics. Each point is represented as a
coordinate in a Point graphics primitive. All the various graphics options used in this case are
also given.
In[2]:= InputForm@%D
Out[2]//InputForm= Graphics[{{{}, {Hue[0.67, 0.6, 0.6], Point[{{1., 2.},
{2., 3.}, {3., 5.}, {4., 7.}, {5., 11.}, {6., 13.},
{7., 17.}, {8., 19.}, {9., 23.}, {10., 29.}, {11.,
31.}, {12., 37.}, {13., 41.}, {14., 43.}, {15.,
47.}, {16., 53.}, {17., 59.}, {18., 61.}, {19.,
67.}, {20., 71.}}]}, {}}},
{AspectRatio -> GoldenRatio^(-1), Axes -> True,
AxesOrigin -> {0, 0}, PlotRange ->
{{0., 20.}, {0., 71.}}, PlotRangeClipping -> True,
PlotRangePadding -> {Scaled[0.02], Scaled[0.02]}}]

Each complete piece of graphics in Mathematica is represented as a graphics object. There are
several different kinds of graphics object, corresponding to different types of graphics. Each
kind of graphics object has a definite head which identifies its type.

Graphics@listD general two-dimensional graphics


Graphics3D@listD general three-dimensional graphics

Graphics objects in Mathematica.

The functions like Plot and ListPlot discussed in "The Structure of Graphics and Sound" all
work by building up Mathematica graphics objects, and then displaying them.

You can create other kinds of graphical images in Mathematica by building up your own graph-
ics objects. Since graphics objects in Mathematica are just symbolic expressions, you can use
all the standard Mathematica functions to manipulate them.

Graphics objects are automatically formatted by the Mathematica front end as graphics upon
output. Graphics may also be printed as a side effect using the Print command.
Visualization and Graphics 35

The Graphics object is computed by Mathematica, but its output is suppressed by the
semicolon.
In[3]:= Graphics@Circle@DD;
2+2
Out[3]= 4

A side effect output can be generated using the Print command. It has no Out@D label
because it is a side effect.
In[4]:= Print@Graphics@Circle@DDD;
2+2

Out[4]= 4

Show@g, optsD display a graphics object with new options specified by opts
Show@g1 ,g2 ,…D display several graphics objects combined using the
options from g1
Show@g1 ,g2 ,…,optsD display several graphics objects with new options specified
by opts

Displaying graphics objects.

Show can be used to change the options of an existing graphic or to combine multiple graphics.

This uses Show to adjust the Background option of an existing graphic.


In[5]:= g1 = Plot@Sin@xD, 8x, 0, 2 Pi<D;
Show@g1, Background Ø PinkD
1.0

0.5

Out[8]=
1 2 3 4 5 6

-0.5

-1.0
36 Visualization and Graphics

This uses Show to combine two graphics. The values used for PlotRange and other options are
based upon those which were set for the first graphic.
In[6]:= Show@8g1, Graphics@Circle@DD<D
1.0

0.5

Out[9]=
-1 1 2 3 4 5 6

-0.5

-1.0

Here, new options are specified for the entire graphic.


In[7]:= Show@8g1, Graphics@Circle@DD<, PlotRange Ø All, AspectRatio Ø AutomaticD
1.0
0.5
Out[10]=
-1 1 2 3 4 5 6
-0.5
-1.0

Graphics directives Examples: RGBColor , Thickness


Graphics options Examples: PlotRange, Ticks , AspectRatio ,
ViewPoint

Local and global ways to modify graphics.

Given a particular list of graphics primitives, Mathematica provides two basic mechanisms for
modifying the final form of graphics you get. First, you can insert into the list of graphics primi-
tives certain graphics directives, such as RGBColor, which modify the subsequent graphical
elements in the list. In this way, you can specify how a particular set of graphical elements
should be rendered.

This creates a two-dimensional graphics object that contains the Polygon graphics primitive.
In[8]:= poly = Polygon@Table@N@8Cos@n Pi ê 5D, Sin@n Pi ê 5D<D, 8n, 0, 5<DD;
Graphics@polyD

Out[8]=
Visualization and Graphics 37

InputForm shows the complete graphics object.


In[9]:= InputForm@%D
Out[9]//InputForm= Graphics[Polygon[{{1., 0.}, {0.8090169943749475,
0.5877852522924731}, {0.30901699437494745,
0.9510565162951535}, {-0.30901699437494745,
0.9510565162951535}, {-0.8090169943749475,
0.5877852522924731}, {-1., 0.}}]]

This takes the graphics primitive created above, and adds the graphics directives RGBColor
and EdgeForm .
In[10]:= Graphics@8RGBColor@0.3, 0.5, 1D, EdgeForm@Thickness@0.01DD, poly<D

Out[10]=

By inserting graphics directives, you can specify how particular graphical elements should be
rendered. Often, however, you want to make global modifications to the way a whole graphics
object is rendered. You can do this using graphics options.

By adding the graphics option Frame you can modify the overall appearance of the graphics.
In[11]:= Show@%, Frame -> TrueD

0.8

0.6

Out[11]= 0.4

0.2

0.0
-1.0 -0.5 0.0 0.5 1.0

InputForm shows that the option was introduced into the resulting Graphics object.
In[12]:= InputForm@%D
Out[12]//InputForm= Graphics[{RGBColor[0.3, 0.5, 1],
EdgeForm[Thickness[0.01]],
Polygon[{{1., 0.}, {0.8090169943749475,
0.5877852522924731}, {0.30901699437494745,
0.9510565162951535}, {-0.30901699437494745,
0.9510565162951535}, {-0.8090169943749475,
0.5877852522924731}, {-1., 0.}}]}, {Frame -> True}]
38 Visualization and Graphics

You can specify graphics options in Show. As a result, it is straightforward to take a single
graphics object, and show it with many different choices of graphics options.

Notice however that Show always returns the graphics objects it has displayed. If you specify
graphics options in Show, then these options are automatically inserted into the graphics objects
that Show returns. As a result, if you call Show again on the same objects, the same graphics
options will be used, unless you explicitly specify other ones. Note that in all cases new options
you specify will overwrite ones already there.

Options@gD give a list of all graphics options for a graphics object


Options@g,optD give the setting for a particular option

Finding the options for a graphics object.

Some graphics options can be used as options to visualization functions which generate graph-
ics. Options which can take the right-hand side of Automatic are sometimes resolved into
specific values by the visualization functions.

Here is a plot.
In[13]:= zplot = Plot@Abs@Zeta@1 ê 2 + I xDD, 8x, 0, 10<, PlotRange Ø AutomaticD

1.4

1.2

Out[13]=
1.0

0.8

2 4 6 8 10

Mathematica uses an internal algorithm to compute an explicit value for PlotRange in the
resulting graphic.
In[14]:= Options@zplot, PlotRangeD
Out[14]= 8PlotRange Ø 880., 10.<, 80.526253, 1.54919<<<

FullGraphics@gD translate objects specified by graphics options into lists of


explicit graphics primitives

Finding the complete form of a piece of graphics.

When you use a graphics option such as Axes, the Mathematica front end automatically draws
objects such as axes that you have requested. The objects are represented merely by the
Visualization and Graphics 39

option values rather than by a specific list of graphics primitives. Sometimes, however, you
may find it useful to represent these objects as the equivalent list of graphics primitives. The
function FullGraphics gives the complete list of graphics primitives needed to generate a
particular plot, without any options being used.

This plots a list of values.


In[15]:= ListPlot@Table@EulerPhi@nD, 8n, 10<DD
6

4
Out[15]=
3

2 4 6 8 10

FullGraphics yields a graphics object that includes graphics primitives representing axes and
so on.
In[16]:= Short@InputForm@FullGraphics@%DD, 6D
Graphics@8888<, 8Hue@0.67, 0.6, 0.6D, Point@881., 1.<, 82., 1.<, 83., 2.<, 84., 2.<, 85.,
Out[16]//Short= 4.<, 86., 2.<, 87., 6.<, 88., 4.<, 89., 6.<, 810., 4.<<D<, 8<<<, 88GrayLevel@0.D,
AbsoluteThickness@0.25D, Line@882., 1.<, 82., 1.0505635621484342<<D<, <<56>><<D

Two-Dimensional Graphics Elements

Point@8x,y<D point at position x, y


Line@88x1 ,y1 <,8x2 ,y2 <,…<D line through the points 8x1 , y1 <, 8x2 , y2 <, …
Rectangle@8xmin ,ymin <,8xmax ,ymax <D filled rectangle
Polygon@88x1 ,y1 <,8x2 ,y2 <,…<D filled polygon with the specified list of corners
Circle@8x,y<,rD circle with radius r centered at x, y
Disk@8x,y<,rD filled disk with radius r centered at x, y
Raster@88a11 ,a12 ,…<,8a21 ,…<,…<E rectangular array of gray levels between 0 and 1

Text@expr,8x,y<D the text of expr, centered at x, y (see "Graphics Primitives


for Text")

Basic two-dimensional graphics elements.

Here is a line primitive.


In[1]:= sawline = Line@Table@8n, H- 1L ^ n<, 8n, 6<DD
Out[1]= Line@881, -1<, 82, 1<, 83, -1<, 84, 1<, 85, -1<, 86, 1<<D
40 Visualization and Graphics

This shows the line as a two-dimensional graphics object.


In[2]:= sawgraph = Graphics@sawlineD

Out[2]=

This redisplays the line, with axes added.


In[3]:= Show@%, Axes -> TrueD
1.0

0.5

Out[3]=
2 3 4 5 6
-0.5

-1.0

You can combine graphics objects that you have created explicitly from graphics primitives with
ones that are produced by functions like Plot.

This produces an ordinary Mathematica plot.


In[4]:= Plot@Sin@Pi xD, 8x, 0, 6<D
1.0

0.5

Out[4]=
1 2 3 4 5 6

-0.5

-1.0

This combines the plot with the sawtooth picture made above.
In[5]:= Show@%, sawgraphD
1.0

0.5

Out[5]=
1 2 3 4 5 6

-0.5

-1.0
Visualization and Graphics 41

You can combine different graphical elements simply by giving them in a list. In two-dimen-
sional graphics, Mathematica will render the elements in exactly the order you give them. Later
elements are therefore effectively drawn on top of earlier ones.

Here are two blue Rectangle graphics elements.


In[6]:= 8Blue, Rectangle@81, - 1<, 82, - 0.6<D, Rectangle@84, .3<, 85, .8<D<
Out[6]= 8RGBColor@0, 0, 1D, Rectangle@81, -1<, 82, -0.6<D, Rectangle@84, 0.3<, 85, 0.8<D<

This draws the rectangles on top of the line that was defined above.
In[7]:= Graphics@8sawline, %<D

Out[7]=

The Polygon graphics primitive takes a list of x, y coordinates, corresponding to the corners of a
polygon. Mathematica joins the last corner with the first one, and then fills the resulting area.

Here are the coordinates of the corners of a regular pentagon.


In[8]:= pentagon = Table@8Sin@2 Pi n ê 5D, Cos@2 Pi n ê 5D<, 8n, 5<D

5 5 1 5 5 1
Out[8]= :: + , -1 + 5 >, : - , -1 - 5 >,
8 8 4 8 8 4

5 5 1 5 5 1
:- - , -1 - 5 >, :- + , -1 + 5 >, 80, 1<>
8 8 4 8 8 4

This displays the pentagon. With the default choice of aspect ratio, the pentagon looks some-
what squashed.
In[9]:= Graphics@Polygon@pentagonDD

Out[9]=
42 Visualization and Graphics

Point@8pt1 ,pt2 ,…<D a multipoint consisting of points at pt1 , pt2 , …

Line@8line1 ,line2 ,…<D a multiline consisting of lines line1 , line2 , …


Polygon@8poly1 ,poly2 ,…<D a multipolygon consisting of polygons poly1 , poly2 , …

Primitives which can take multiple elements.

A large number of points can be represented by putting a list of coordinates inside of a single
Point primitive. Similarly, a large number of lines or polygons can be represented as a list of
coordinate lists. This representation is efficient and can generally be rendered more quickly by
the Mathematica front end. Graphics directives such as RGBColor apply uniformly to the entire
set of primitives.

This creates a multipolygon based upon the set of coordinates defined previously.
In[10]:= Graphics@Polygon@8pentagon, 1 + .5 pentagon, 1.5 + .2 pentagon<DD

Out[10]=

Here is a multipoint which is colored blue.


In[11]:= Graphics@8Blue, Point@Table@8x, Cos@xD<, 8x, - 6, 6, .2<DD<, Axes Ø TrueD
1.0
0.5
Out[11]=
-6 -4 -2 2 4 6
-0.5
-1.0

Circle@8x,y<,rD a circle with radius r centered at the point 8x, y<


CircleA9x,y=,9rx ,ry =E an ellipse with semi-axes rx and ry

Circle@8x,y<,r,8theta1 ,theta2 <D a circular arc


CircleA an elliptical arc
9x,y=,9rx ,ry =,8theta1 ,theta2 <E
DiskA9x,y=,rE , etc. filled disks

Circles and disks.


Visualization and Graphics 43

This shows two circles with radius 2.


In[12]:= Graphics@8Circle@80, 0<, 2D, Circle@81, 1<, 2D<D

Out[12]=

This shows a sequence of disks with progressively larger semi-axes in the x direction, and
progressively smaller ones in the y direction.
In[13]:= Graphics@Table@Disk@83 n, 0<, 8n ê 4, 2 - n ê 4<D, 8n, 4<DD

Out[13]=

Mathematica allows you to generate arcs of circles, and segments of ellipses. In both cases, the
objects are specified by starting and finishing angles. The angles are measured counterclock-
wise in radians with zero corresponding to the positive x direction.

This draws a 140È wedge centered at the origin.


In[14]:= Graphics@Disk@80, 0<, 1, 80, 140 Degree<DD

Out[14]=

RasterA array of gray levels between 0 and 1


98a11 ,a12 ,…<,9a21 , … }, … }]
Raster@888a11 ,o11 <,…<,…<D array of gray levels with opacity between 0 and 1
44 Visualization and Graphics

Raster@888r11 ,g11 ,b11 <,…<,…<D array of rgb values between 0 and 1


Raster@888r11 ,g11 ,b11 ,o11 <,…<,…<D array of rgb values with opacity between 0 and 1
Raster@array,88xmin ,ymin <, array of gray levels between zmin and zmax drawn in the
8xmax ,ymax <<,8zmin ,zmax <D rectangle defined by 8xmin , ymin < and 8xmax , ymax <

Raster-based graphics elements.

Here is a 4×4 array of values between 0 and 1.


In[15]:= modtab = Table@Mod@i, jD ê 3, 8i, 4<, 8j, 4<D êê N
Out[15]= 880., 0.333333, 0.333333, 0.333333<,
80., 0., 0.666667, 0.666667<, 80., 0.333333, 0., 1.<, 80., 0., 0.333333, 0.<<

This uses the array of values as gray levels in a raster.


In[16]:= Graphics@Raster@modtabDD

Out[16]=

This shows two overlapping copies of the raster.


In[17]:= Graphics@8Raster@modtab, 880, 0<, 82, 2<<D, Raster@modtab, 881.5, 1.5<, 83, 2<<D<D

Out[17]=

The ColorFunction option can be used to change the default way in which a Raster is
colored.
In[18]:= Graphics@8Raster@modtab, ColorFunction Ø HueD<D

Out[18]=
Visualization and Graphics 45

Graphics Directives and Options


When you set up a graphics object in Mathematica, you typically give a list of graphical ele-
ments. You can include in that list graphics directives which specify how subsequent elements
in the list should be rendered.

In general, the graphical elements in a particular graphics object can be given in a collection of
nested lists. When you insert graphics directives in this kind of structure, the rule is that a
particular graphics directive affects all subsequent elements of the list it is in, together with all
elements of sublists that may occur. The graphics directive does not, however, have any effect
outside the list it is in.

The first sublist contains the graphics directive GrayLevel.


In[1]:= 88GrayLevel@0.5D, Rectangle@80, 0<, 81, 1<D<, Rectangle@81, 1<, 82, 2<D<
Out[1]= 88GrayLevel@0.5D, Rectangle@80, 0<, 81, 1<D<, Rectangle@81, 1<, 82, 2<D<

Only the rectangle in the first sublist is affected by the GrayLevel directive.
In[2]:= Graphics@%D

Out[2]=

GrayLevel@iD gray level between 0 (black) and 1 (white)


RGBColor@r,g,bD color with specified red, green and blue components, each
between 0 and 1
Hue@hD color with hue h between 0 and 1
Hue@h,s,bD color with specified hue, saturation and brightness, each
between 0 and 1

Basic Mathematica color specifications.


46 Visualization and Graphics

Mathematica accepts the names of many colors directly as color specifications. These color
names, such as Red, Gray, LightGreen and Purple, are implemented as variables which evalu-
ate to an RGBColor specification. The color names can be used interchangeably with color
directives.

The first plot is colored with a color name, while the second one has a fine-tuned RGBColor
specification.
In[3]:= Plot@8BesselI@1, xD, BesselI@2, xD<, 8x, 0, 5<,
PlotStyle -> 88Red<, 8RGBColor@0.3, 0.7, 0.1D<<D
25

20

15
Out[3]=
10

1 2 3 4 5

The function Hue@hD provides a convenient way to specify a range of colors using just one
parameter. As h varies from 0 to 1, Hue@hD runs through red, yellow, green, cyan, blue,
magenta, and back to red again. Hue@h, s, bD allows you to specify not only the “hue”, but also
the “saturation” and “brightness” of a color. Taking the saturation to be equal to one gives the
deepest colors; decreasing the saturation toward zero leads to progressively more “washed out”
colors.

When you give a graphics directive such as RGBColor, it affects all subsequent graphical ele-
ments that appear in a particular list. Mathematica also supports various graphics directives
which affect only specific types of graphical elements.

The graphics directive PointSize@dD specifies that all Point elements which appear in a graph-
ics object should be drawn as circles with diameter d. In PointSize, the diameter d is
measured as a fraction of the width of your whole plot.

Mathematica also provides the graphics directive AbsolutePointSize@dD, which allows you to
1
specify the “absolute” diameter of points, measured in fixed units. The units are of an inch,
72

approximately printer’s points.

PointSize@dD give all points a diameter d as a fraction of the width of the


whole plot
AbsolutePointSize@dD give all points a diameter d measured in absolute units

Graphics directives for points.


Visualization and Graphics 47

Here is a list of points.


In[4]:= Table@Point@8n, Prime@nD<D, 8n, 6<D
Out[4]= 8Point@81, 2<D, Point@82, 3<D, Point@83, 5<D, Point@84, 7<D, Point@85, 11<D, Point@86, 13<D<

This makes each point have a diameter equal to one-tenth of the width of the plot.
In[5]:= Graphics@8PointSize@0.1D, %<, PlotRange -> AllD

Out[5]=

Here each point has size 3 in absolute units.


In[6]:= ListPlot@Table@Prime@nD, 8n, 20<D, PlotStyle -> AbsolutePointSize@3DD
70
60
50
40
Out[6]= 30
20
10

5 10 15 20

Thickness@wD give all lines a thickness w as a fraction of the width of the


whole plot
AbsoluteThickness@wD give all lines a thickness w measured in absolute units
Dashing@8w1 ,w2 ,…<D show all lines as a sequence of dashed segments, with
lengths w1 , w2 , …
AbsoluteDashing@8w1 ,w2 ,…<D use absolute units to measure dashed segments

Graphics directives for lines.

This generates a list of lines with different absolute thicknesses.


In[7]:= Table@8AbsoluteThickness@nD, Line@880, 0<, 8n, 1<<D<, 8n, 4<D
Out[7]= 88AbsoluteThickness@1D, Line@880, 0<, 81, 1<<D<, 8AbsoluteThickness@2D, Line@880, 0<, 82, 1<<D<,
8AbsoluteThickness@3D, Line@880, 0<, 83, 1<<D<, 8AbsoluteThickness@4D, Line@880, 0<, 84, 1<<D<<
48 Visualization and Graphics

Here is a picture of the lines.


In[8]:= Graphics@%D

Out[8]=

The Dashing graphics directive allows you to create lines with various kinds of dashing. The
basic idea is to break lines into segments which are alternately drawn and omitted. By changing
the lengths of the segments, you can get different line styles. Dashing allows you to specify a
sequence of segment lengths. This sequence is repeated as many times as necessary in draw-
ing the whole line.

This gives a dashed line with a succession of equal-length segments.


In[9]:= Graphics@8Dashing@80.05, 0.05<D, Line@88- 1, - 1<, 81, 1<<D<D

Out[9]=

This gives a dot-dashed line.


In[10]:= Graphics@8Dashing@80.01, 0.05, 0.05, 0.05<D, Line@88- 1, - 1<, 81, 1<<D<D

Out[10]=

Dashing can be turned off by specifying an empty list. Here, Dashing is turned off for only
the second line.
In[11]:= Graphics@8Dashing@80.05<D, Line@880, 0<, 81, 1<<D,
8Dashing@8<D, Line@880, 0<, 82, 1<<D<,
Line@880, 0<, 83, 1<<D<D

Out[11]=
Visualization and Graphics 49

Graphics directives which require a numerical size specification can also accept values of Tiny,
Small, Medium, and Large. For each directive, these values have been fine-tuned to produce an
appearance which will seem appropriate to the human eye.

This specifies a large thickness with medium dashing.


In[12]:= Plot@Sin@xD, 8x, 0, 2 Pi<, PlotStyle Ø 88Dashing@8Medium<D, Thickness@LargeD<<D
1.0

0.5

Out[12]=
1 2 3 4 5 6

-0.5

-1.0

This specifies that the entire multipoint should use large, green points.
In[13]:= Graphics@8PointSize@LargeD, Green, Point@880, 0<, 81, 0.5<, 82, 0<, 81, - .5<<D<D

Out[13]=

One way to use Mathematica graphics directives is to insert them directly into the lists of graph-
ics primitives used by graphics objects. Sometimes, however, you want the graphics directives
to be applied more globally, and for example to determine the overall “style” with which a
particular type of graphical element should be rendered. There are typically graphics options
which can be set to specify such styles in terms of lists of graphics directives.

PlotStyle->style specify a style to be used for all curves in Plot


PlotStyle->88style1 <,8style2 <,…< specify styles to be used (cyclically) for a sequence of
curves in Plot
MeshStyle->style specify a style to be used for a mesh in density and surface
graphics
BoxStyle->style specify a style to be used for the bounding box in three-
dimensional graphics

Some graphics options for specifying styles.


50 Visualization and Graphics

This generates a plot in which all curves are specified to use the same style.
In[14]:= Plot@8BesselJ@1, xD, BesselJ@2, xD<,
8x, 0, 10<, PlotStyle -> 88Thickness@0.02D, Gray<<D
0.6

0.4

0.2
Out[14]=

2 4 6 8 10
-0.2

A different PlotStyle expression can be used to give specific styles to each curve.
In[15]:= Plot@8BesselJ@1, xD, BesselJ@2, xD<, 8x, 0, 10<,
PlotStyle -> 88Thickness@0.02D, Gray<, 8Red<<D
0.6

0.4

0.2
Out[15]=

2 4 6 8 10
-0.2

The various “style options” allow you to specify how particular graphical elements in a plot
should be rendered. Mathematica also provides options that affect the rendering of the whole
plot.

Background->color specify the background color for a plot


BaseStyle->color specify the base style for a plot, affecting elements not
affected by PlotStyle
Prolog->g give graphics to render before a plot is started
Epilog->g give graphics to render after a plot is finished

Graphics options that affect whole plots.

This draws the plot in white on a gray background.


In[16]:= Plot@Sin@Sin@xDD, 8x, 0, 10<, Background Ø Gray, PlotStyle Ø WhiteD

0.5

Out[16]=
2 4 6 8 10

-0.5
Visualization and Graphics 51

This makes the axes white as well.


In[17]:= Show@%, BaseStyle Ø WhiteD

0.5

Out[17]=
2 4 6 8 10

-0.5

Coordinate Systems for Two-Dimensional Graphics


When you set up a graphics object in Mathematica, you give coordinates for the various graphi-
cal elements that appear. When Mathematica renders the graphics object, it has to translate
the original coordinates you gave into "display coordinates" which specify where each element
should be placed in the final display area.

PlotRange->99xmin , the range of original coordinates to include in the plot


xmax =,9ymin ,ymax ==

Option which determines translation from original to display coordinates.

When Mathematica renders a graphics object, one of the first things it has to do is to work out
what range of original x and y coordinates it should actually display. Any graphical elements
that are outside this range will be clipped, and not shown.

The option PlotRange specifies the range of original coordinates to include. As discussed in
"Options for Graphics", the default setting is PlotRange -> Automatic, which makes Mathemat-
ica try to choose a range which includes all "interesting" parts of a plot, while dropping
"outliers". By setting PlotRange -> All, you can tell Mathematica to include everything. You
can also give explicit ranges of coordinates to include.

This sets up a polygonal object whose corners have coordinates between roughly ± 1.
In[1]:= obj = Polygon@Table@8Sin@n Pi ê 10D, Cos@n Pi ê 10D< + 0.05 H- 1L ^ n, 8n, 20<DD;
52 Visualization and Graphics

In this case, the polygonal object fills almost the whole display area.
In[2]:= Graphics@objD

Out[2]=

Specifying an explicit PlotRange allows you to zoom in on a section of a graphic.


In[3]:= Graphics@obj, PlotRange Ø 880, 1<, All<D

Out[3]=

AspectRatio ->r make the ratio of height to width for the display area equal
to r
AspectRatio ->Automatic determine the shape of the display area from the original
coordinate system

Specifying the shape of the display area.

What we have discussed so far is how Mathematica translates the original coordinates you
specify into positions in the final display area. What remains to discuss, however, is what the
final display area is like.

On most computer systems, there is a certain fixed region of screen or paper into which the
Mathematica display area must fit. How it fits into this region is determined by its “shape” or
aspect ratio. In general, the option AspectRatio specifies the ratio of height to width for the
final display area.
Visualization and Graphics 53

It is important to note that the setting of AspectRatio does not affect the meaning of the
scaled or display coordinates. These coordinates always run from 0 to 1 across the display area.
What AspectRatio does is to change the shape of this display area.

For two-dimensional graphics, AspectRatio is set by default to Automatic. This determines the
aspect ratio from the original coordinate system used in the plot instead of setting it at a fixed
value. One unit in the x direction in the original coordinate system corresponds to the same
distance in the final display as one unit in the y direction. In this way, objects that you define in
the original coordinate system are displayed with their "natural shape".

This generates a graphic object corresponding to a regular hexagon. With the default value of
AspectRatio -> Automatic, the aspect ratio of the final display area is determined from the
original coordinate system, and the hexagon is shown with its "natural shape".
In[4]:= Graphics@Polygon@Table@8Sin@n Pi ê 3D, Cos@n Pi ê 3D<, 8n, 6<DDD

Out[4]=

This renders the hexagon in a display area whose height is three times its width.
In[5]:= Show@%, AspectRatio -> 3D

Out[5]=
54 Visualization and Graphics

Sometimes, you may find it convenient to specify the display coordinates for a graphical ele-
ment directly. You can do this by using scaled coordinates Scaled@8sx, sy<D rather than 8x, y<.
The scaled coordinates are defined to run from 0 to 1 in x and y, with the origin taken to be at
the lower-left corner of the plot range.

8x,y< original coordinates


Scaled@8sx,sy<D coordinates scaled to the plot range
ImageScaled @8sx,sy<D coordinates scaled to the display area

Coordinate systems for two-dimensional graphics.

The display area is significantly larger than the plot range due to the frame label.
In[6]:= g = Graphics@8Green, Disk@D<, PlotRange Ø 2,
Frame Ø True, FrameLabel Ø 8Style@"x", LargeD<D
2

0
Out[6]=

-1

-2
-2 -1 0 1 2

Using Scaled coordinates, the rectangle falls at the origin, which is at the center of the speci-
fied plot range.
In[7]:= Show@g, Prolog Ø 8Rectangle@Scaled@80.25, 0.25<D, Scaled@80.75, 0.75<DD<D
2

0
Out[7]=

-1

-2
-2 -1 0 1 2

x
Visualization and Graphics 55

Using ImageScaled coordinates, the rectangle falls at exactly the center of the graphic, which
does not coincide with the center of the plot range.
In[8]:= Show@g, Prolog Ø 8Rectangle@ImageScaled@80.25, 0.25<D, ImageScaled@80.75, 0.75<DD<D
2

0
Out[8]=

-1

-2
-2 -1 0 1 2

x
When you use 8x, y<, Scaled@8sx, sy<D or ImageScaled @8sx, sy<D, you are specifying position
either completely in original coordinates, or completely in scaled coordinates. Sometimes,
however, you may need to use a combination of these coordinate systems. For example, if you
want to draw a line at a particular point whose length is a definite fraction of the width of the
plot, you will have to use original coordinates to specify the basic position of the line, and
scaled coordinates to specify its length.

You can use Scaled@8dsx, dsy<, 8x, y<D to specify a position using a mixture of original and
scaled coordinates. In this case, 8x, y< gives a position in original coordinates, and 8dsx, dsy<
gives the offset from the position in scaled coordinates.

CircleA8x,y<,Scaled@sxDE a circle whose radius is scaled to the width of the plot range

DiskA8x,y<,Scaled@sxDE a disk whose radius is scaled to the width of the plot range

FontSize->Scaled@sxD specification for a font size scaled to the width of the plot
range

Some places where Scaled can be used with a single argument.


56 Visualization and Graphics

Both the radius of the circle and the size of the font are specified in Scaled values.
In[9]:= Graphics@
8Circle@80, 0<, Scaled@0.3DD, FontSize Ø Scaled@0.2D, Text@"some text", 80, 0<D<D

Out[9]=
some text

Scaled@8sdx,sdy<,8x,y<D scaled offset from original coordinates


ImageScaled @8sdx,sdy<,8x,y<D image scaled offset from original coordinates
Offset@8adx,ady<,8x,y<D absolute offset from original coordinates
Offset@8adx,ady<,Scaled@8sx,sy<DD absolute offset from scaled coordinates
OffsetA8adx,ady<, absolute offset from image scaled coordinates
ImageScaled @8sx,sy<DE

Positions specified as offsets.

Each line drawn here has an absolute length of 6 printer’s points.


In[10]:= Graphics@Table@Line@88x, x ^ 2<, Offset@80, 6<, 8x, x ^ 2<D<D, 8x, 10<D, Frame -> TrueD
100

80
Visualization and Graphics 57

60

Out[10]=

40

20

2 4 6 8 10
58 Visualization and Graphics

You can also use Offset inside Circle with just one argument to create a circle with a certain
absolute radius.
In[11]:= Graphics@Table@Circle@8x, x ^ 2<, Offset@82, 2<DD, 8x, 10<D, Frame -> TrueD
100

80

60

Out[11]=

40
Visualization and Graphics 59

20

2 4 6 8 10

In most kinds of graphics, you typically want the relative positions of different objects to adjust
automatically when you change the coordinates or the overall size of your plot. But sometimes
you may instead want the offset from one object to another to be constrained to remain fixed.
This can be the case, for example, when you are making a collection of plots in which you want
certain features to remain consistent, even though the different plots have different forms.

Offset@8adx, ady<, positionD allows you to specify the position of an object by giving an absolute
offset from a position that is specified in original or scaled coordinates. The units for the offset
1
are printer’s points, equal to 72
of an inch.

When you give text in a plot, the size of the font that is used is also specified in printer’s points.
Therefore, a 10-point font, for example, has letters whose basic height is 10 printer’s points.
You can use Offset to move text around in a plot, and to create plotting symbols or icons
which match the size of the text.

Using scaled coordinates, you can specify the sizes of graphical elements as fractions of the size
of the display area. You cannot, however, tell Mathematica the actual physical size at which a
particular graphical element should be rendered. Of course, this size ultimately depends on the
details of your graphics output device, and cannot be determined for certain within Mathemat-
60 Visualization and Graphics

ica. Nevertheless, graphics directives such as AbsoluteThickness discussed in "Graphics Direc-


tives and Options" do allow you to indicate “absolute sizes” to use for particular graphical ele-
ments. The sizes you request in this way will be respected by most, but not all, output devices.
(For example, if you optically project an image, it is neither possible nor desirable to maintain
the same absolute size for a graphical element within it.)

Labeling Two-Dimensional Graphics

Axes->True give a pair of axes


GridLines->Automatic draw grid lines on the plot
Frame->True put axes on a frame around the plot
PlotLabel->"text" give an overall label for the plot

Ways to label two-dimensional plots.

Here is a plot, using the default Axes -> True .


In[1]:= bp = Plot@BesselJ@2, xD, 8x, 0, 10<D

0.4

0.2
Out[1]=
2 4 6 8 10

-0.2

Setting Frame -> True generates a frame with axes, and removes tick marks from the ordi-
nary axes.
In[2]:= Show@bp, Frame -> TrueD

0.4

0.2

Out[2]=
0.0

-0.2

0 2 4 6 8 10
Visualization and Graphics 61

This includes grid lines, which are shown in light gray.


In[3]:= Show@%, GridLines -> AutomaticD

0.4

0.2

Out[3]=
0.0

-0.2

0 2 4 6 8 10

Axes->False draw no axes


Axes->True draw both x and y axes
Axes->9False,True= draw a y axis but no x axis

AxesOrigin->Automatic choose the crossing point for the axes automatically


AxesOrigin->9x,y= specify the crossing point

AxesStyle->style specify the style for axes


AxesStyle->8xstyle,ystyle< specify individual styles for axes
AxesLabel->None give no axis labels
AxesLabel->ylabel put a label on the y axis
AxesLabel->9xlabel,ylabel= put labels on both x and y axes

Options for axes.

This makes the axes cross at the point 85, 0<, and puts a label on each axis.
In[4]:= Show@bp, AxesOrigin -> 85, 0<, AxesLabel -> 8"x", "y"<D
y

0.4

0.2
Out[4]=

x
0 2 4 6 8 10

-0.2

Ticks->None draw no tick marks


Ticks->Automatic place tick marks automatically
Ticks->9xticks,yticks= tick mark specifications for each axis

Settings for the Ticks option.


62 Visualization and Graphics

With the default setting Ticks -> Automatic, Mathematica creates a certain number of major
and minor tick marks, and places them on axes at positions which yield the minimum number
of decimal digits in the tick labels. In some cases, however, you may want to specify the posi-
tions and properties of tick marks explicitly. You will need to do this, for example, if you want to
have tick marks at multiples of p, or if you want to put a nonlinear scale on an axis.

None draw no tick marks

Automatic place tick marks automatically


8x1 ,x2 ,…< draw tick marks at the specified positions
88x1 ,label1 <,8x2 ,label2 <,…< draw tick marks with the specified labels
88x1 ,label1 ,len1 <,…< draw tick marks with the specified scaled lengths
88x1 ,label1 ,8plen1 ,mlen1 <<,…< draw tick marks with the specified lengths in the positive
and negative directions
88x1 ,label1 ,len1 ,style1 <,…< draw tick marks with the specified styles
func a function to be applied to xmin , xmax to get the tick mark
option

Tick mark options for each axis.

This gives tick marks at specified positions on the x axis, and chooses the tick marks automati-
cally on the y axis.
In[5]:= Show@bp, Ticks -> 880, Pi, 2 Pi, 3 Pi<, Automatic<D

0.4

0.2
Out[5]=
p 2p 3p

-0.2

This adds tick marks with no labels at multiples of p ê 2.


In[6]:= Show@bp,
Ticks -> 880, 8Pi ê 2, ""<, Pi, 83 Pi ê 2, ""<, 2 Pi, 85 Pi ê 2, ""<, 3 Pi<, Automatic<D

0.4

0.2
Out[6]=
p 2p 3p

-0.2
Visualization and Graphics 63

Particularly when you want to create complicated tick mark specifications, it is often convenient
to define a "tick mark function" which creates the appropriate tick mark specification given the
minimum and maximum values on a particular axis.

This defines a function which gives a list of tick mark positions with a spacing of 1.
In[7]:= units@xmin_, xmax_D := Range@Floor@xminD, Floor@xmaxD, 1D

This uses the units function to specify tick marks for the x axis.
In[8]:= Show@bp, Ticks -> 8units, Automatic<D

0.4

0.2

Out[8]=

1 2 3 4 5 6 7 8 9 10

-0.2

Frame->False draw no frame


Frame->True draw a frame around the plot
FrameStyle->style specify a style for the frame
FrameStyle-> specify styles for each edge of the frame
88left,right<,8bottom,top<<
FrameLabel->None give no frame labels
FrameLabel-> put labels on edges of the frame
88left,right<,8bottom,top<<
RotateLabel ->False do not rotate text in labels
FrameTicks->None draw no tick marks on frame edges
FrameTicks->Automatic position tick marks automatically
FrameTicks-> specify tick marks for frame edges
88left,right<,8bottom,top<<

Options for frame axes.

The Axes option allows you to draw a single pair of axes in a plot. Sometimes, however, you
may instead want to show the scales for a plot on a frame, typically drawn around the whole
plot. The option Frame allows you effectively to draw four axes, corresponding to the four edges
of the frame around a plot.
64 Visualization and Graphics

This draws frame axes, and labels each of them.


In[9]:= Show@bp, Frame -> True,
FrameLabel -> 88"left label", "right label"<, 8"bottom label", "top label"<<D
top label

0.4

0.2

right label
left label

Out[9]=
0.0

-0.2

0 2 4 6 8 10
bottom label

GridLines->None draw no grid lines


GridLines->Automatic position grid lines automatically
GridLines->9xgrid,ygrid= specify grid lines in analogy with tick marks

Options for grid lines.

Grid lines in Mathematica work very much like tick marks. As with tick marks, you can specify
explicit positions for grid lines. There is no label or length to specify for grid lines. However, you
can specify a style.

This generates x but not y grid lines.


In[10]:= Show@bp, GridLines -> 8Automatic, None<D

0.4

0.2

Out[10]=

2 4 6 8 10

-0.2

Insetting Objects in Graphics


"Redrawing and Combining Plots" describes how you can make regular arrays of plots using
GraphicsGrid. Using the Inset graphics primitive, however, you can combine and superim-
pose plots in any way.
Visualization and Graphics 65

Inset@obj, posD specifies that the inset should be placed at position pos in
the graphic
Inset@obj,pos, opos, sizeD render an object with a given size so that point opos in obj is
positioned at point pos in the containing graphic
Inset@obj,pos, opos, size, dirsD specifies that the axes of the inset should be oriented in
directions dirs

Creating an inset.

Here is a plot.
In[1]:= p1 = Plot@8Sin@xD, Sin@2 xD<, 8x, 0, 2 p<,
ImageSize Ø 200, Frame Ø True, Background Ø LightYellowD
1.0

0.5

Out[1]= 0.0

-0.5

-1.0
0 1 2 3 4 5 6

This creates a plot within a parametric plot.


In[2]:= ParametricPlot@8Sin@xD, Sin@2 xD<, 8x, 0, 4 p<, Epilog Ø Inset@p1, 8.3, - .5<DD
1.0

0.5

1.0
Out[2]=
-1.0 -0.5 0.5 1.0
0.5

0.0
-0.5

-0.5

-1.0 -1.0

Here is a three-dimensional plot.


In[3]:= p3 = Plot3D@Sin@xD Exp@yD, 8x, - 5, 5<, 8y, - 2, 2<D

Out[3]=
66 Visualization and Graphics

This creates a two-dimensional graphics object that contains two differently sized copies of the
three-dimensional plot.
In[4]:= Graphics@8Inset@p3, - 81, 1<, Center, 82, 2<D,
Inset@p3, 8.5, .5<, Center, 83, 3<D<, PlotRange Ø 2D

Out[4]=

Here are rotated and skewed plots inset in a graphic.


In[5]:= Graphics@8
Inset@p1, 81, 0<, Center, 81, 1<, 81, 1<D,
Inset@p1, 82, 0<, Center, 81, 1<, 881, 0<, 81, 1<<D
<D

1.0
0.5
6

Out[5]= 0.0
5

-0.5
4
0
1.

-1.0
3
5

0 1 2 3 4 5 6
0.
0

2
0.
-1 .5

1
-0
.0
0

Mathematica can render plots, arbitrary 2D or 3D graphics, cells, and text within an Inset.
Notice that in general the display area for graphics objects will be sized so as to touch at least
one pair of edges of the Inset.
Visualization and Graphics 67

Density and Contour Plots

DensityPlot @ f ,8x,xmin ,xmax <,8y,ymin ,ymax <D


make a density plot of f
ContourPlot @ f ,8x,xmin ,xmax <,8y,ymin ,ymax <D
make a contour plot of f as a function of x and y

Density and contour plots.

This gives a density plot of sinHxL sinHyL. Lighter regions show higher values of the function.
In[1]:= DensityPlot@Sin@xD Sin@yD, 8x, - 2, 2<, 8y, - 2, 2<D

Out[1]=

option name default value


ColorFunction Automatic what colors to use for shading; Hue uses a
sequence of hues
Mesh None whether to draw a mesh
PlotPoints Automatic number of initial sample points in each
direction
MaxRecursion Automatic the maximum number of recursive subdivi -
sion steps to do

Some options for DensityPlot .


68 Visualization and Graphics

You can include a mesh like this.


In[2]:= DensityPlot@Sin@xD Sin@yD, 8x, - 2, 2<, 8y, - 2, 2<, Mesh Ø 19D

Out[2]=

In a density plot, the color of each point represents the value at that point of the function being
plotted. By default, the color ranges from black to white through intermediate shades of blue as
the value of the function increases. In general, however, you can specify other “color maps” for
the relation between the value at a point and its color. The option ColorFunction allows you to
specify a function which is applied to the function value to find the color at any point. The color
function may return any Mathematica color directive, such as GrayLevel, Hue or RGBColor. A
common setting to use is ColorFunction -> Hue.

This uses different hues to represent different values.


In[3]:= DensityPlot@Sin@xD Sin@yD, 8x, - 2, 2<, 8y, - 2, 2<, ColorFunction Ø HueD

Out[3]=

A significant resource for customized color functions is the ColorData function. ColorData
provides many customized sets of colors which can be used directly by ColorFunction.
Visualization and Graphics 69

This shows a list of the gradients which can be accessed using ColorData.
In[4]:= ColorData@"Gradients"D
Out[4]= 8DarkRainbow, Rainbow, Pastel, Aquamarine, BrassTones, BrownCyanTones, CherryTones, CoffeeTones,
FuchsiaTones, GrayTones, GrayYellowTones, GreenPinkTones, PigeonTones, RedBlueTones,
RustTones, SiennaTones, ValentineTones, AlpineColors, ArmyColors, AtlanticColors,
AuroraColors, AvocadoColors, BeachColors, CandyColors, CMYKColors, DeepSeaColors, FallColors,
FruitPunchColors, IslandColors, LakeColors, MintColors, NeonColors, PearlColors, PlumColors,
RoseColors, SolarColors, SouthwestColors, StarryNightColors, SunsetColors, ThermometerColors,
WatermelonColors, RedGreenSplit, DarkTerrain, GreenBrownTerrain, LightTerrain,
SandyTerrain, BlueGreenYellow, LightTemperatureMap, TemperatureMap, BrightBands, DarkBands<

This DensityPlot is identical to the one above, but uses the "SolarColors" gradient.
In[5]:= DensityPlot@Sin@xD Sin@yD, 8x, - 2, 2<,
8y, - 2, 2<, ColorFunction Ø ColorData@"SolarColors"DD

Out[5]=

This gives a contour plot of the function.


In[6]:= ContourPlot@Sin@xD Sin@yD, 8x, - 2, 2<, 8y, - 2, 2<D

Out[6]=
70 Visualization and Graphics

A contour plot gives you essentially a “topographic map” of a function. The contours join points
on the surface that have the same height. The default is to have contours corresponding to a
sequence of equally spaced z values. Contour plots produced by Mathematica are by default
shaded, in such a way that regions with higher z values are lighter.

option name default value

ColorFunction Automatic what colors to use for shading; Hue uses a


sequence of hues
Contours Automatic the total number of contours, or the list of
z values for contours
PlotRange 9Full,Full,Automatic= the range of values to be included; you can
specify 8zmin , zmax <, All or Automatic, or
a list 8xrange, yrange, zrange<

ContourShading Automatic how to shade the regions; None leaves the


regions blank, or a list of colors can be
provided
PlotPoints Automatic number of initial sample points in each
direction
MaxRecursion Automatic the maximum number of recursive subdivi -
sion steps to do

Some options for ContourPlot .

This shows the plot with no shading.


In[7]:= ContourPlot@Sin@xD Sin@yD, 8x, - 2, 2<, 8y, - 2, 2<, ContourShading Ø NoneD

Out[7]=
Visualization and Graphics 71

This cycles the colors used for contour regions between light red and light purple.
In[8]:= ContourPlot@Sin@xD Sin@yD, 8x, - 2, 2<,
8y, - 2, 2<, ContourShading Ø 8LightRed, LightPurple<D

Out[8]=

Both DensityPlot and ContourPlot use an adaptive algorithm that subdivides parts of the plot
region to obtain more sample points for a smoother representation of the function you are
plotting. Because the number of sample points is always finite, however, it is possible that
features of your function will sometimes be missed. When necessary, you can increase the
number of sample points by increasing the values of the PlotPoints and MaxRecursion
options.

One point to notice is that whereas a curve generated by Plot may be inaccurate if your func-
tion varies too quickly in a particular region, the shape of contours generated by ContourPlot
can be inaccurate if your function varies too slowly. A rapidly varying function gives a regular
pattern of contours, but a function that is almost flat can give irregular contours. You can
typically overcome this by increasing the value of PlotPoints or MaxRecursion.

Three-Dimensional Graphics Primitives


One of the most powerful aspects of graphics in Mathematica is the availability of three-dimen-
sional as well as two-dimensional graphics primitives. By combining three-dimensional graphics
primitives, you can represent and render three-dimensional objects in Mathematica.
72 Visualization and Graphics

Point@8x,y,z<D point with coordinates x, y, z


Line@88x1 ,y1 ,z1 <,8x2 ,y2 ,z2 <,…<D line through the points 8x1 , y1 , z1 <, 8x2 , y2 , z2 <, …
Polygon@88x1 ,y1 ,z1 <,8x2 ,y2 ,z2 <,…<D
filled polygon with the specified list of corners
Cuboid@8xmin ,ymin ,zmin <,8xmax ,ymax ,zmax <D
cuboid
Text@expr,8x,y,z<D text at position 8x, y, z< (see "Graphics Primitives for
Text")

Three-dimensional graphics elements.

Every time you evaluate rcoord, it generates a random coordinate in three dimensions.
In[1]:= rcoord := RandomReal@1., 83<D

This generates a list of 20 random points in three-dimensional space.


In[2]:= pts = Table@Point@rcoordD, 820<D;

Here is a plot of the points.


In[3]:= Graphics3D@ptsD

Out[3]=

This gives a plot showing a line through 10 random points in three dimensions.
In[4]:= Graphics3D@Line@Table@rcoord, 810<DDD

Out[4]=
Visualization and Graphics 73

If you give a list of graphics elements in two dimensions, Mathematica simply draws each
element in turn, with later elements obscuring earlier ones. In three dimensions, however,
Mathematica collects together all the graphics elements you specify, then displays them as
three-dimensional objects, with the ones in front in three-dimensional space obscuring those
behind.

Every time you evaluate rantri, it generates a random triangle in three-dimensional space.
In[5]:= rantri := Polygon@Table@rcoord, 83<DD

This draws a single random triangle.


In[6]:= Graphics3D@rantriD

Out[6]=

This draws a collection of 5 random triangles. The triangles in front obscure those behind.
In[7]:= Graphics3D@Table@rantri, 85<DD

Out[7]=

By creating an appropriate list of polygons, you can build up any three-dimensional object in
Mathematica. Thus, for example, all the surfaces produced by ParametricPlot3D are repre-
sented essentially as lists of polygons.

Point@8pt1 ,pt2 ,…<D a multipoint consisting of points at pt1 , pt2 , …

Line@8line1 ,line2 ,…<D a multiline consisting of lines line1 , line2 , …


Polygon@8poly1 ,poly2 ,…<D a multipolygon consisting of polygons poly1 , poly2 , …

Primitives which can take multiple elements.


74 Visualization and Graphics

As with the two-dimensional primitives, some three-dimensional graphics primitives have multi-
coordinate forms which are a more efficient representation. When dealing with a very large
number of primitives, using these multi-coordinate forms where possible can both reduce the
memory footprint of the resulting graphic and make it render much more quickly.

rantricoords defines merely the coordinates of a random triangle.


In[8]:= rantricoords := Table@rcoord, 83<D

Using the multi-coordinate form of Polygon , this efficiently represents a very large number of
triangles.
In[9]:= Graphics3D@Polygon@Table@rantricoords, 810 000<DDD

Out[9]=

Mathematica allows polygons in three dimensions to have any number of vertices in any configu-
ration. Depending upon the locations of the vertices, the resulting polygons may be non-copla-
nar or nonconvex. When rendering non-coplanar polygons, Mathematica will break the polygon
into triangles, which are planar by definition, before rendering it.

The non-coplanar polygon is broken up into triangles. The interior edge joining the triangles is
not outlined like the outer edges of the Polygon primitive.
In[10]:= Graphics3D@8Polygon@880, 0, 0<, 80, 0, 1<, 81, 1, 0<, 81, 0, 1<<D<D

Out[10]=

You might also like