Visualization and Graphics: Wolfram Mathematica Tutorial Collection
Visualization and Graphics: Wolfram Mathematica Tutorial Collection
Visualization and Graphics: Wolfram Mathematica Tutorial Collection
Basic Plotting
Plot@ f ,8x,x0 ,x1 ,…,xk <D plot f over a series of segments, potentially breaking the
curve at each of the xi
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<<
2.5
Out[6]= 2.0
1.5
1 2 3 4
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
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.
Some of the options for Plot . These can also be used in Show .
4 Visualization and Graphics
0.5
Out[1]=
0.5 1.0 1.5 2.0 2.5 3.0
-0.5
-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
True do this
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.
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
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.
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
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
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
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
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
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
2 4 6 8 10
-0.2
-0.4
0.2
4 6 8 10
Out[5]= -0.2
-0.4
-0.6
-0.8
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.
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.)
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
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.
1.5
1.0
Out[4]=
0.5
5 10 15 20
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===
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.
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]=
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]=
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.
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]=
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.
80
60
Out[2]=
40
20
2 4 6 8 10
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
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;
Out[8]=
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.
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
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]=
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]=
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 plotting functions. The second group of functions are defined in standard Mathematica
packages.
Out[1]= 0.1
0.01
1 2 3 4 5 6
30 Visualization and Graphics
In[4]:= BarChart@pD
Out[4]=
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.
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.
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.
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.
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
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.
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 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
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.
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
Show can be used to change the options of an existing graphic or to combine multiple graphics.
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
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
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.
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<<<
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.
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
Out[2]=
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.
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.
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.
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
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]=
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.
Out[14]=
Out[16]=
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
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.
Only the rectangle in the first sublist is affected by the GrayLevel directive.
In[2]:= Graphics@%D
Out[2]=
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
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]=
5 10 15 20
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.
Out[9]=
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.
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.
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.
0.5
Out[16]=
2 4 6 8 10
-0.5
Visualization and Graphics 51
0.5
Out[17]=
2 4 6 8 10
-0.5
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]=
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
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.
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
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
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
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
0.4
0.2
Out[3]=
0.0
-0.2
0 2 4 6 8 10
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
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.
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
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
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
0.4
0.2
right label
left label
Out[9]=
0.0
-0.2
0 2 4 6 8 10
bottom label
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.
0.4
0.2
Out[10]=
2 4 6 8 10
-0.2
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
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
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]=
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
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]=
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.
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]=
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.
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.
Every time you evaluate rcoord, it generates a random coordinate in three dimensions.
In[1]:= rcoord := RandomReal@1., 83<D
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
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.
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.
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]=