Mathematica Tutorial Graphics
Mathematica Tutorial Graphics
August 2012
Mathematica Graphics Tutorial
Table of Contents
2
The Division of Statistics + Scientific Computation, The University of Texas at Austin
Mathematica Graphics Tutorial
Section 1: Introduction
Mathematica is capable of generating a wide range of graphics, from a simple plot of a function,
to three dimensional animations of complex physical systems. This document will concentrate on
the most fundamental and most widely used of the Mathematica plotting capabilities, the use of
the Plot function to generate two dimensional graphics.
Many of the functions demonstrated here produce graphical results. These results are not
displayed on this page. Hypertext links from the function calls lead to gif images of their results.
The images used in this document were obtained by grabbing the screen image of the plot with
XV and saving it as a gif.
Plot is the simplest and most frequently used of the graphics functions. Calls to the Plot function
are of the form:
This generates a plot of the function f as var varies from varmin to varmax. For example, to plot
Sin[theta] for 0 < theta < 2Pi use:
Plot is, of course, not limited to operating on functions. As long as it depends on a single
variable, almost any expression that Mathematica can evaluate can be used. For example:
Optional arguments to the Plot command provide a great deal of control over the appearance,
layout, and information content of the plot. Options are set by passing :
at the end of the argument list. Options[Function] returns a list of the Function's default options.
Options[Plot]
returns
3
The Division of Statistics + Scientific Computation, The University of Texas at Austin
Mathematica Graphics Tutorial
1
{AspectRatio -> -----------, Axes -> Automatic,
GoldenRatio
One of the most commonly used Plot options is AxesLabel. AxesLabel attaches labels to the
axes. Assigning it a single value places that label on the y axis:
Assigning AxesLabel a list of two values, {xlabel, ylabel}, causes Mathematica to use these
values as labels for the x and y axes respectively.
An option closely related to AxesLabel is PlotLabel. The PlotLabel option associates a label
with the entire plot.
4
The Division of Statistics + Scientific Computation, The University of Texas at Austin
Mathematica Graphics Tutorial
Mathematica graphics, once generated, can be redrawn or altered with the Show command.
Show changes properties such as the aspect ratio, which, if any, grid lines to draw, or which
colors are used in the plot. The Viewpoint and PlotRange attributes can be manipulated to
produce panning and zooming effects. Show is, however, limited in that it can not produce any
new data. The curve is generated by the Plot command, Show can only alter how it is displayed.
In[1]:=
Plot[Sin[x^2],{x,0,2 Pi}]
Several examples will be given where Show is used to modify the presentation of this plot.
As described above, the AxesLabel option to Plot attaches labels to the axes of a Mathematica
plot. If the arguments to this option are quoted, they will be placed on the plot exactly as typed.
However, if the arguments are not quoted then they are displayed in Mathematica's
OutputForm [Mathematica, PP 343-346].
Show[%,AxesLabel->{x,Sin[x^2]}]
This means that fractions and exponents will be presented in a two-dimensional form. It also
means that Mathematica will try to evaluate any expression that it is given. In the above case, if x
is undefined then:
Sin[x^2]
becomes
2
Sin[x ]
and this will produce the desired label. However, if x is defined, perhaps to be 3, then
Sin[x^2]
will evaluate to Sin[9], which is not suitable as a label for a plot axis. If a variable's definition
interferes with its use in a plot label, remove the definition for the variable with:
Remove[variable]
5
The Division of Statistics + Scientific Computation, The University of Texas at Austin
Mathematica Graphics Tutorial
Where variable will be replaced with the name of the variable to be removed.
Subscripted[f[x,y,z],2,-1]
The first argument f[x,y,z], is a variable and an argument list. The second argument to
Subscripted tells which of the arguments of f should be used as subscripts. In this case 2 means
take the first two (x and y) as subscripts. The last argument to Subscripted describes the
arguments that are to be taken as superscripts. The -1 denotes the last element of the list (z). This
produces:
z
f
x,y
Show[%1,AxesLabel->Subscripted[f[x,y,z],2,-1]]
The Text function provides much finer control over where the text is placed [Mathematica, PP
469-471]. The Text function takes two arguments, a text string, and the {x,y} coordinates for the
center of the string. To place labels on our plot using this function use:
Show[%1,Epilog->{Text[Sin[x^2],{-0.355,1.25}],
Text[x,{6.9,-0.11}]},
PlotRange -> All]
For 2-D graphics the same coordinate system that is shown on the axes of the plot can be used.
However, for 3-D graphics Mathematica uses a special coordinate system to position objects.
Positioning text in this case will take a bit of trial and error. Some of the front ends to
Mathematica provide a method to determine the coordinates of an arbitrary point on a plot. For
the Macintosh front end, select a plot, then hold down the command key (the one with the apple
on it) while the cursor is over the plot, the coordinates of the cursor will be displayed in the
lower left corner of the Mathematica window. The X interface uses the meta key and displays
the coordinates in the lower right corner. Other front ends may provide a similar method to
determine coordinates on a plot.
The Epilog option causes the text to be drawn after other parts of the plot. This has two
advantages. First, the text will be drawn over any other parts of the graph and can not be
obscured by them. Further, if we attempt to draw the text as part of the main graph, the axes of
the graph will extend to include the labels; we do not want this.
6
The Division of Statistics + Scientific Computation, The University of Texas at Austin
Mathematica Graphics Tutorial
The FontForm function [see P468 of Mathematica] changes the font of the displayed text. The
FontForm function is inserted around the text argument to the Text Mathematica function. So
that instead of:
Text[Sin[x^2],{-0.355,1.25}]
one has
Text[FontForm[Sin[x^2],
{"Courier-Oblique",10}],
{-0.355,1.45}]
2
Sin[x ]
in the Courier-Oblique font of 10pt size and places it at the coordinates {-0.355,1.45}. A full
Plot command using this would look like:
Show[%1,Epilog->{Text[FontForm[Sin[x^2],
{"Courier-Oblique",10}],
{-0.355,1.45}],
Text[FontForm[x,
{"Courier-Oblique",10}],
{6.9,-0.11}]},
PlotRange -> All]
These options and functions can be combined to produce many effects, for example Greek letters
can be used in plot labels:
7
The Division of Statistics + Scientific Computation, The University of Texas at Austin
Mathematica Graphics Tutorial
Providing a list of RGBColors for the PlotStyle option sets the color for each curve of the plot:
This generates the first curve (Sin[theta]) with the first color (red), and the second curve
(Cos[theta]) in the second color (blue). Choosing appropriate colors for each curve in a plot
makes it easy to follow the curves even when they cross or become intertwined.
Colors are set for each element of the plot using the optional arguments. PlotStyle sets the style,
in this case the color, for the curves that are plotted. The tick marks and the text that labels them
are usually drawn in the DefaultColor. Finally the style for the axes are set with with the
AxesStyle argument.
Plot[{Sin[theta],Cos[theta]},
{theta,0,2 Pi},
PlotStyle -> {RGBColor[0,1,0],
8
The Division of Statistics + Scientific Computation, The University of Texas at Austin
Mathematica Graphics Tutorial
RGBColor[0,1,1]},
DefaultColor -> RGBColor[0,0,1],
AxesStyle -> RGBColor[1,0,0]]
While an esoteric feature, it is possible to set the style for each individual tick mark. This is
documented here primarily because the procedure described in the Mathematica Reference
Manual is not correct. Note in the example below the values for the Ticks argument are of the
form:
Plot[Sin[theta],{theta,0,2 Pi},
Ticks -> {{{1,"1",.01,{RGBColor[1,0,0]}},
{2,"2",.01,{RGBColor[0,1,0]}},
{3,"3",.01,{RGBColor[0,0,1]}},
{4,"4",.01,{RGBColor[1,0,0]}},
{5,"5",.01,{RGBColor[0,1,0]}},
{6,"6",.01,{RGBColor[0,0,1]}}},
{{1,"1",.01,{RGBColor[1,0,1]}}}}]
Drawing legends is not a built in part of Mathematica. To draw legends it is necessary to read in
the standard Mathematica package Graphics`Legend`, with the command:
<< Graphics`Legend`
This need only be done once each session before the Legend package is used.
9
The Division of Statistics + Scientific Computation, The University of Texas at Austin
Mathematica Graphics Tutorial
The Legend package only accepts text in a single font for each label within the legend. More
complex labels can be built using the technique illustrated above for building axes labels. For
example the previous plot can be redisplayed with:
Epilog is used to draw this text on top of all the other elements of the plot, including the legend.
Frequently a single plot is not sufficient. One might wish to represent the solution to a
differential equation for several values of a parameter, or the value of a series where the series is
summed to different orders. This is done with the GraphicsArray function. GraphicsArray
arranges a set of graphics objects into a regular pattern, an array. If we generate:
and
Show[GraphicsArray[{Row1, Row2}]]
Alternatively all the frames can be generated with a single call to Table:
Show[GraphicsArray[Partition[Plots,3]]]
10
The Division of Statistics + Scientific Computation, The University of Texas at Austin
Mathematica Graphics Tutorial
Where the Partition function breaks the original list of six graphs, into two lists, each containing
three graphics objects. The second argument to Partition specifies the length of the resulting
lists.
Sometimes, especially if the parameter that varies from frame to frame is time, we will want to
display the frames one at a time in series, rather than all at once in a GraphicsArray.
Mathematica has a number of ways to generate animations. There are some features that they all
have in common. Animation in Mathematica is accomplished by first generating a series of
images, then displaying them in rapid succession.
In[1]:=
Solution = DSolve[{ x''[t] + kd x'[t] + x[t] == 0,
x[0] == 10,
x'[0] == 0},
x[t], t]
Out[1]:=
2
((-kd - Sqrt[-4 + kd ]) t)/2) 5 kd
{{x[t] -> E^ (5 - --------------) +
2
Sqrt[-4 + kd ]
2
((-kd + Sqrt[-4 + kd ]) t)/2) 5 kd
E^ (5 + --------------)}}
2
Sqrt[-4 + kd ]
We now have an equation with two free parameters. This allows the generation of a series of
graphs of x vs t, each with a differing value of kd. Those graphs can then be displayed as a
movie. The first step is accomplished with:
In[2]:=
Table[Plot[x[t] /. Solution, {t,0,20},
PlotRange -> {-10, 10},
AxesLabel -> {Time, Amplitude}],
{kd, 0, 3, .08}];
This generates a long series of graphs. The PlotRange was specified explicitly to maintain a
constant vertical scale from frame to frame. To prepare this series of frames to become a movie
double-click on the second cell bracket, the one that covers all the frames of the movie. This will
collapse the frames into a single cell.
To play such a collapsed set of frames as a movie, double click on the top image. There may be a
short wait before the movie starts, especially if there are a large number of frames.
11
The Division of Statistics + Scientific Computation, The University of Texas at Austin
Mathematica Graphics Tutorial
Another option with the Macintosh version of Mathematica is to select Convert to QuickTime...
from the Graph menu while a collapsed set of frames is selected. This will write to disk a
QuickTime movie built from the Mathematica graphics frames.
In this movie it is not immediately obvious what is varying from frame to frame. It would help if,
along with each frame, there was displayed an indicator of the varying quantity. To do this make
each frame a GraphicsArray; one element of the array will be the same plot that makes up the
entire frame in the above movie, the other element of the array will be a bar graph showing the
value of kd, the parameter that varies from frame to frame.
Like legends, bar charts are not a built in part of Mathematica, but are included in the standard
Mathematica packages. First, read in the package that contains the BarChart function.
<<Graphics`Graphics`
Then generate the movie that contains two images in each frame.
Do[Show[GraphicsArray[{Plot[x[t] /. Solution,
{t,0,20},
PlotRange -> {-10, 10},
AxesLabel -> {Time, Amplitude},
DisplayFunction -> Identity],
BarChart[{kd},
PlotRange -> {0, 3},
AxesOrigin -> {2,0},
AspectRatio -> 3,
BarLabels -> "kd",
DisplayFunction -> Identity]},
GraphicsSpacing -> 0]],
{kd,0,3,0.08}]
Do[Show[...], {kd,0,3,0.08}]
Repeats the Show command for kd varying from 0 to 3 in increments of 0.08. The Show
command draws the frames of the movie. Each frame of the movie is of the form
The GraphicsSpacing -> 0 argument reduces as much as possible the separation between
the left and right sides of the frame.
The left side of each frame is generated by the same Plot function that was used in the previous
movie, except that it has the additional argument DisplayFunction -> Identity. This
prevents the plot from being drawn to the screen at the time of creation. The frames for this
12
The Division of Statistics + Scientific Computation, The University of Texas at Austin
Mathematica Graphics Tutorial
movie are drawn by the Show command after they have been built by the GraphicsArray
function.
The right side of each frame is generated by the BarChart[list] function. In this case the list
consists of one element, the kd parameter. Several optional arguments are also passed to
BarChart: PlotRange -> {0, 3} keeps the vertical scale constant from frame to frame,
AxesOrigin -> {2,0} shifts the vertical axis to the right, AspectRatio -> 3 sets the
height to width ratio, BarLabels -> "kd" places the kd label at the base of the bar, and as
before DisplayFunction -> Identity suppresses the drawing of the plot until the Show function
is called to display the entire GraphicsArray.
Section 8: References
Mathematica, A System for Doing Mathematics by Computer is the reference manual for
Mathematica . This book describes all the capabilities of Mathematica and gives a large number
of simple examples of their use. Copies of this manual are available in the Student
Microcomputing Facility, SMF 223, the SMF documentation room, for in lab use.
13
The Division of Statistics + Scientific Computation, The University of Texas at Austin