You are on page 1of 45

ECM6 Computational Methods :

Slide 1 of 14

Lecture 8
Overview of Graphical Functions
Brian G. Higgins
Department of Chemical Engineering & Materials Science
University of California, Davis
April 2014, Hanoi, Vietnam

ECM6Lecture8Vietnam_2014.nb

Topics for Lecture 8


In this lecture we give a brief over view of the following topics

1. Plotting functions
2. Plot Options
3. Adding Text to a plot
4. List and Contour Plots
5. Extracting data from plot functions
In[1]:=

Remove@myFunctions, myFun, myFun2, myF, myG, feqnD

ECM6Lecture8Vietnam_2014.nb

Plotting Functions: The Basics


Mathematica has several plotting routines that allow you to plot a function of a single variable or multiple
variables. In this lecture we will examine The Plot function and how to set its options. We will also
consider several axillary plot functions: ListPlot, ParametricPlot and ImplicitPlot.
Mathematica's built-in function called Plot that can be used to plot an expression (exp) in the interval a
to b. The plot function is specified as
Plot[exp, {x, xmin, xmax}, options]

Example 1
In the example given below we plot Sin[x] in the interval 0 to 3p. Since we have not specified any
options, Mathematica has used the default values for the plot options.
In[2]:=

Plot@Sin@xD, 8x, 0, 3 p<D


1.0

0.5

Out[2]=

-0.5

-1.0

Example 2
The function Plot can also be used to plot two or more functions on the same axes. The functions to be
plotted are grouped as a list with the brackets { }. In the example given below we plot Sin[x] and
Cos[x] on the same axes in the interval 0 to 3p

ECM6Lecture8Vietnam_2014.nb

In[3]:=

Plot@8Sin@xD, Cos@xD<, 8x, 0, 3 p<D


1.0

0.5

Out[3]=

-0.5

-1.0

Suppose we would like to plot the functions x 2 for a range of n values and have the plots displayed on
the same axes. We showed in the previous example that we could do this by creating a list of the
desired functions {expr1, expr2, ...etc.} and then using the list as the first argument of the Plot function. An alternative method is to make use of the Table function. For example,
In[4]:=
Out[4]=

myFunctions = Table@t ^ n, 8n, 5<D


9t, t2 , t3 , t4 , t5 =

produces a list of functions (note that we did not specify nmin, and Mathematica used the default
nmin=1). We can now plot this list of functions
In[5]:=

Plot@myFunctions, 8t, 0, 1<D


1.0

0.8

0.6
Out[5]=

0.4

0.2

0.2

0.4

0.6

0.8

1.0

Example 3:
There are circumstances when it is useful to use the function Evaluate, to ensure the argument of Plot
is evaluated before an attempt is made to generate the plot. Suppose we would like to plot a function
that is defined by an integral
In[6]:=

myFun@a_D := Integrate@Cos@a xD Exp@- x 2D, 8x, 0, 3<D

Since the assignment for myfun[t] is delayed (we used the delayed assignment command :=), the
function is not evaluated until it is called. To see what the function looks like we evaluate it:

ECM6Lecture8Vietnam_2014.nb

In[7]:=

myFun@aD
2 I32 - Cos@3 aD + 2 a Sin@3 aDM

Out[7]=

I1 + 4 a2 M 32

Next, we plot the function over the interval 1 t 3 and use the command //Timing to determine how
much CPU time it took for Mathematica to make the plot:
In[8]:=

Column@Timing@Plot@myFun@tD, 8t, 1, 5<DDD


135.177844

0.35
0.30
0.25
Out[8]= 0.20
0.15
0.10
0.05
2

The plot took approximately 44 seconds of CPU time (on a MacPro 2.8 Ghz). The output from this
operation is a list - the first argument of the list is the time estimate the second argument is the Plot. By
wrapping the output with Column we format the arguments of the list as a column.

Example 4:
Let us now perform the same operation but wrap the function in the Evaluate command in the Plot
function:
In[9]:=

Column@Timing@Plot@Evaluate@myFun@tDD, 8t, 1, 5<DDD


0.309691

0.35
0.30
0.25
Out[9]= 0.20
0.15
0.10
0.05
2

The second plot took approximately 0.5 seconds, almost a 10 fold reduction in CPU time. The reason
for this is related to the way that Plot evaluates fun[t]. First, Plot substitutes a value for t into fun[t] and
only then is the integration done. This sequence of steps is repeated every time Plot calls fun[t].
Recall Plot does not evaluate its own argument. On the other hand, when we use Evaluate, the integration is done once within Plot. It is instructive to contrast what happens if we defined fun[t] with an
immediate assignment (the command =), versus a delayed assignment (the command :=), viz.,
In[10]:=

myFun2@a_D = Integrate@Cos@a xD Exp@- x 2D, 8x, 0, 3<D


2 I32 - Cos@3 aD + 2 a Sin@3 aDM

Out[10]=

I1 + 4 a2 M 32

With an immediate assignment the integration is done at the outset, and consequently the CPU requirement for the Plot routine is not excessive as the following example illustrates:

ECM6Lecture8Vietnam_2014.nb

In[11]:=

Column@Timing@Plot@myFun2@tD, 8t, 1, 5<DDD


0.021892

0.35
0.30
0.25
Out[11]= 0.20
0.15
0.10
0.05
2

Here is another example of the difficulty one can get in because Plot does not evaluate its arguments.
Suppose we want to Plot the derivative of Sin[x]. Thus for the argument of Plot we use D[Sin[x],x]. As
the example below shows Mathematica is unable to produce the plot

Example 5:
Here is another example of the difficulty one can get in because Plot does not evaluate its arguments.
Suppose we want to Plot the derivative of Sin[x]. Thus for the argument of Plot we use D[Sin[x],x]. As
the example below shows Mathematica is unable to produce the plot
In[12]:=

Plot@x Sin@xD, 8x, 0, 3 p<D


General::ivar : 0.00019253474977000304` is not a valid variable.
General::ivar : 0.19253494211241037` is not a valid variable.
General::ivar : 0.38487734947505076` is not a valid variable.
General::stop : Further output of General::ivar will be suppressed during this calculation.
1.0

0.5

Out[12]=

-0.5

-1.0

Because Plot does not evaluate the derivative, a numerical value, say a, is passed to the variable x and
then Mathematica attempts to plot D[Sin[a],a], where a is a real number. Of course, the derivative
function with a real variable substituted for x is meaningless and so the plot fails to execute. If we wrap
the expression with Evaluate the plot is executed

ECM6Lecture8Vietnam_2014.nb

In[13]:=

Plot@Evaluate@x Sin@xDD, 8x, 0, 3 p<D


1.0

0.5

Out[13]=

-0.5

-1.0

Alternatively, we can use a replacement rule to avoid having a numerical value substituted for the
arguments of the derivative:
In[14]:=

Remove@yD;
PlotAy Sin@yD .y x, 8x, 0, 3 p<E
1.0

0.5

Out[15]=

-0.5

-1.0

ECM6Lecture8Vietnam_2014.nb

Exploring Plot Options For Axes, PlotLabel and Ticks


Let us consider more carefully the options available in Plot. Each option is a rule of the form
OptionName OptionValue

To see what options are available we can wrap the function Plot with the command Options
In[16]:=

Out[16]=

Options@PlotD
:AlignmentPoint Center, AspectRatio

, Axes True,
GoldenRatio
AxesLabel None, AxesOrigin Automatic, AxesStyle 8<, Background None,
BaselinePosition Automatic, BaseStyle 8<, ClippingStyle None,
ColorFunction Automatic, ColorFunctionScaling True, ColorOutput Automatic,
ContentSelectable Automatic, CoordinatesToolOptions Automatic,
DisplayFunction $DisplayFunction, Epilog 8<, Evaluated Automatic,
EvaluationMonitor None, Exclusions Automatic, ExclusionsStyle None,
Filling None, FillingStyle Automatic, FormatType TraditionalForm,
Frame False, FrameLabel None, FrameStyle 8<, FrameTicks Automatic,
FrameTicksStyle 8<, GridLines None, GridLinesStyle 8<,
ImageMargins 0., ImagePadding All, ImageSize Automatic,
ImageSizeRaw Automatic, LabelStyle 8<, MaxRecursion Automatic,
Mesh None, MeshFunctions 81 &<, MeshShading None, MeshStyle Automatic,
Method Automatic, PerformanceGoal $PerformanceGoal, PlotLabel None,
PlotLegends None, PlotPoints Automatic, PlotRange 8Full, Automatic<,
PlotRangeClipping True, PlotRangePadding Automatic, PlotRegion Automatic,
PlotStyle Automatic, PreserveImageOptions Automatic, Prolog 8<,
RegionFunction HTrue &L, RotateLabel True, TargetUnits Automatic,
Ticks Automatic, TicksStyle 8<, WorkingPrecision MachinePrecision>

In this section we will discuss several options that are used quite frequently for the Plot function. Other
plot functions (e.g. ListPlot, ParametricPlot, ImplicitPlot) have similar options that a user can specify;
once you have mastered the specification of options for one function, it is easy to see how to use them
for other functions.

AxesLabel
For the plot function their are several "Axes" related options. These include AxesLabel, AxesStyle, and
Ticks The AxesLabel option allows you to label the axes of your plot. The syntax is
AxesLabel->{XaxisLabel,YaxisLabel}

where XaxisLabel is any string variable , i.e., variable enclosed with " ". Here is an example

ECM6Lecture8Vietnam_2014.nb

In[17]:=

Plot@Sin@xD, 8x, 0, 3 p<, AxesLabel 8"x", "SinHxL"<D


SinHxL
1.0

0.5

Out[17]=

x
2

-0.5

-1.0

PlotLabel
The PlotLabel option allows you to give a title to the plot. The syntax is
PlotLabel->title

where title is a string. Here is an example


In[18]:=

Plot@Sin@xD, 8x, 0, 3 p<, PlotLabel "My Sin Plot"D


My Sin Plot
1.0

0.5

Out[18]=

-0.5

-1.0

Sometimes it is necessary to change the vertical position of the label relative to the plot. One can use
the "new line" given by the \n command to force the appearance of a new line in the heading. Here is an
example

10

ECM6Lecture8Vietnam_2014.nb

In[19]:=

Plot@Sin@xD, 8x, 0, 3 p<, PlotLabel "My Sin Plot\n\nApril 23, 2006"D


My Sin Plot
April 23, 2006
1.0

0.5
Out[19]=

-0.5

-1.0

AxesStyle
The AxesStyle option allows one to alter the appearance of the horizontal and vertical axes of the plot.
The syntax for this option is
AxesStyle ->{{StyleDirective for x-axis},{StyleDirective for y-axis}}

Here is an example where we change the appearance of the axes.


In[20]:=

Plot@8Sin@xD, Cos@xD<, 8x, 0, 3 p<,


AxesStyle 88Thickness@0.008D, Red<, 8Dashing@80.005<D, Thickness@0.008D, Blue<<D
1.0

0.5

Out[20]=

-0.5

-1.0

The syntax for the directive Dashing is described below


In[21]:=

? Dashing
Dashing@8r1 , r2 , <D is a two-dimensional graphics directive specifying
that lines that follow are to be drawn dashed, with successive segments of lengths r1 ,
r2 , Hrepeated cyclicallyL. The ri are given as a fraction of the total width of the graph.
Dashing@rD is equivalent to Dashing@8r, r<D.

In Version 7 we can also use the built in functions Thick and Thin to specify the thickness of a line

ECM6Lecture8Vietnam_2014.nb

In[22]:=

11

? Thin
Thin is a graphics directive that specifies that lines which follow should be drawn thin.

Another set of directives are Large, Medium, Small and Tiny. For example
In[23]:=

? Small
Small is a style or option setting that specifies that objects should be small.

Here we use Tiny to specify the dashing


In[24]:=

Plot@8Sin@xD, Cos@xD<, 8x, 0, 3 p<,


AxesStyle 88Thin, Red<, 8Dashing@TinyD, Thick, Blue<<D
1.0

0.5

Out[24]=

-0.5

-1.0

Ticks
The option Ticks allows one to specify the tick marks on the axes. Note that Ticks->True is the default
value. The syntax for individual ticks is
Ticks 88x1 , x2 , <, 8y1 , y2 , <<

Here is an example where we specify what the ticks should be


In[25]:=

Plot@8Sin@xD, Cos@xD<, 8x, 0, 3 p<, Ticks 880, p, 2 p, 3 p<, 8- 1, 0, 1<<D


1

Out[25]=

-1

2p

3p

12

ECM6Lecture8Vietnam_2014.nb

We can also specify what the label should be for each tick mark. The syntax in that case is
Ticks 888x1 , label1 <, 8x2 , label2 <, <, 88y1 , lable1 <, 8y2 , label2 <, <<
In[26]:=

Plot@8Sin@xD, Cos@xD<, 8x, 0, 3 p<,


Ticks 880, 8p, "Pi"<, N@2 pD, 83 p, "3Pi"<<, 8- 1, 0, 1<<D
1

Out[26]=

Pi

-1

6.28319

3Pi

ECM6Lecture8Vietnam_2014.nb

13

Exploring Plot Options: PlotRange PlotStyle


PlotRange Option
The PlotRange option determines the range of the dependent and independent variables that will be
displayed in the plot. If we want to restrict the range of the vertical axis the syntax is
PlotRange {ymin, ymax}

For example, suppose in the Sin plot shown earlier we want restrict the view for values of Sin@xD > 0.
Then the range specification is shown below
In[27]:=

Plot@Sin@xD, 8x, 0, 3 p<, PlotRange 80, 1<D


1.0

0.8

0.6
Out[27]=

0.4

0.2

Whereas, if we want to specify the range for the independent variable (along the horizontal axis) as
well, then the format for PlotRange is
PlotRange {{xmin, xmax},{ymin, ymax}
In[28]:=

Plot@Sin@xD, 8x, 0, 3 p<, PlotRange 880, 4<, 80, 1<<D


1.0

0.8

0.6
Out[28]=

0.4

0.2

0.0

Alternative we may want to have a plot that has the vertical range specified automatically by Mathematica, and restrict the horizontal range as in this example

14

ECM6Lecture8Vietnam_2014.nb

Alternative we may want to have a plot that has the vertical range specified automatically by Mathematica, and restrict the horizontal range as in this example

PlotStyle Related Options


The syntax for the PlotStyle option is
PlotStyle Style Directive

The Style Directive is a graphic primitive that allows the user to specify how the plot should be drawn,
e.g.. line thickness, color, broken line, etc. We will discuss the following style directives:
Thickness@valueD, Dashing@8d1 , d2 , <D, GrayLevel[value] Hue[h,s,b], RGBColor[red, green
blue]

Here is an example where we change the thickness and the gray level. Note if you want to apply more
than one Style Directive, you must enclose them using { }, i.e.
PlotStyle->{StyleDirective1 , StyleDirective2 , }

In the following example our plot has a specified thickness, and a specified GrayLevel:
In[29]:=

Plot@Sin@xD, 8x, 0, 3 p<, PlotStyle 8Thick, GrayLevel@0.7D<D


1.0

0.5

Out[29]=

-0.5

-1.0

Here is another example that makes use of Dashing@8d1 , d2 <D and RGBColor[r, b, g]. In this example
d1, d2 are the lengths of the drawn versus un-drawn segments of the plot, and the arguments in RGBColor [r, g, b] define the mix of colors with each element in the range {0,1}.

ECM6Lecture8Vietnam_2014.nb

In[30]:=

Plot@Sin@xD, 8x, 0, 3 p<, PlotStyle 8Dashing@80.02, 0.03<D, RGBColor@0.8, 0, 0.7D<D


1.0

0.5

Out[30]=

-0.5

-1.0

We can also use the default values for dashing by using the function Dashed
In[31]:=

Plot@Sin@xD, 8x, 0, 3 p<, PlotStyle 8Dashed, RGBColor@0.8, 0, 0.7D<D


1.0

0.5

Out[31]=

-0.5

-1.0

If we have more than one plot, we can apply a style directive to each plot using the syntax
PlotStyle {8StyleDirectiveHsL for Plot 1<, {StyleDirective(s) for Plot 2}}

Here is an example

15

16

ECM6Lecture8Vietnam_2014.nb

In[32]:=

Plot@8Sin@xD, Cos@xD<, 8x, 0, 3 p<,


PlotStyle 88Thick, Hue@0.8D<, 8Dashed, RGBColor@0, 0, 1D<<D
1.0

0.5

Out[32]=

-0.5

-1.0

ECM6Lecture8Vietnam_2014.nb

Built-in Colors and Color Functions


The number of built-in color functions has expanded dramatically. Here is a list
Red Green Blue Black White Gray Cyan Magenta Yellow Brown
Orange Pink Purple
LightRed LightGreen LightBlue LightGray LightCyan LightMagenta
LightYellow LightBrown LightOrange LightPink LightPurple

Thus we can create a plot using these functions


In Version 7 the number of built-in color functions has expanded dramatically. Here is a list
Red Green Blue Black White Gray Cyan Magenta Yellow Brown
Orange Pink Purple
LightRed LightGreen LightBlue LightGray LightCyan LightMagenta
LightYellow LightBrown LightOrange LightPink LightPurple

Thus we can create a plot using these functions


In[33]:=

Plot@8Sin@xD, Cos@xD<, 8x, 0, 2 p<, PlotStyle 8Red, LightRed<D


1.0

0.5

Out[33]=

-0.5

-1.0

Note that the color LightRed is really not suitable for coloring lines- it is too light. Better to use the
function Lighter

17

18

ECM6Lecture8Vietnam_2014.nb

In[34]:=

Plot@8Sin@xD, Cos@xD<, 8x, 0, 2 p<, PlotStyle 8Red, Lighter@RedD<D


1.0

0.5

Out[34]=

-0.5

-1.0

The Light colors can best used for coloring a background for the plot
In[35]:=

Plot@8Sin@xD, Cos@xD<, 8x, 0, 2 p<,


PlotStyle 8Red, Lighter@RedD<, Background LightMagentaD
1.0

0.5

Out[35]=

-0.5

-1.0

ECM6Lecture8Vietnam_2014.nb

ColorData
You can also generate a color using Mathematicas ColorData function
In[36]:=

? ColorData
ColorData@"scheme"D gives a function that
generates colors in the named color scheme when applied to parameter values.
ColorData@"scheme", "property"D gives the specified property of a color scheme.
ColorData@"collection"D gives a list of color schemes in a named collection.
ColorData@D gives a list of named collections of color schemes.

Color Schemes
There are 3 named collections or color schemes available
In[37]:=
Out[37]=

ColorData@D
8Gradients, Indexed, Named, Physical<

Let us explore one of these: Gradients


In[38]:=
Out[38]=

ColorData@"Gradients"D
8AlpineColors, Aquamarine, ArmyColors, AtlanticColors, AuroraColors,
AvocadoColors, BeachColors, BlueGreenYellow, BrassTones, BrightBands,
BrownCyanTones, CandyColors, CherryTones, CMYKColors, CoffeeTones, DarkBands,
DarkRainbow, DarkTerrain, DeepSeaColors, FallColors, FruitPunchColors,
FuchsiaTones, GrayTones, GrayYellowTones, GreenBrownTerrain, GreenPinkTones,
IslandColors, LakeColors, LightTemperatureMap, LightTerrain, MintColors,
NeonColors, Pastel, PearlColors, PigeonTones, PlumColors, Rainbow,
RedBlueTones, RedGreenSplit, RoseColors, RustTones, SandyTerrain,
SiennaTones, SolarColors, SouthwestColors, StarryNightColors, SunsetColors,
TemperatureMap, ThermometerColors, ValentineTones, WatermelonColors<

ColorFunction
These built-in color gradients can be used with the ColorFunction option
In[39]:=

? ColorFunction
ColorFunction is an option for graphics
functions that specifies a function to apply to determine colors of elements.

Let us begin our illustration of ColorFunction using the color directive Hue

19

20

ECM6Lecture8Vietnam_2014.nb

In[40]:=

? Hue
Hue@hD is a graphics directive which specifies that objects
which follow are to be displayed, if possible, in a color corresponding to hue h.
Hue@h, s, bD specifies colors in terms of hue, saturation, and brightness.
Hue@h, s, b, aD specifies opacity a.

Note that all arguments sent to ColorFunction are by default scaled between 0 and 1. Thus when we
use Hue we get the full spectrum of colors if we use one of the coordinates as an argument to the
ColorFunction
In[41]:=

Plot@Sinc@xD, 8x, 0, 10<, PlotStyle Thick, ColorFunction Function@8x, y<, Hue@xDDD

Out[41]=

Call that Function is the built-in name for a Pure function or anonymous function
In[42]:=

? Function
Function@bodyD or body & is a pure function. The formal parameters are Hor 1L, 2, etc.
Function@x, bodyD is a pure function with a single formal parameter x.
Function@8x1 , x2 , <, bodyD is a pure function with a list of formal parameters.

Instead of Function we can use the shorthand form body&, as shown below:
In[43]:=

Plot@Sinc@xD, 8x, 0, 10<, PlotStyle Thick, ColorFunction HHue@1D &LD

Out[43]=

If we want to color the graph based on the y-ordinate values we use #2

ECM6Lecture8Vietnam_2014.nb

In[44]:=

Plot@Sinc@xD, 8x, 0, 10<, PlotStyle Thick, ColorFunction HHue@2D &LD

Out[44]=

In[45]:=

Plot@Sinc@xD, 8x, 0, 10<, PlotStyle Thick,


ColorFunction HColorData@"TemperatureMap", 1D &LD

Out[45]=

Note the parentheses are required if you use the shorthand version of the pure function:
This works : ColorFunction (ColorData["TemperatureMap", #1] &)
This does not work: ColorFunction ColorData["TemperatureMap", #1] &
This works: ColorFunction Function[{x,y},ColorData["TemperatureMap"][x]]

Here we scale the color along the curve using the y -ordinate values

21

22

ECM6Lecture8Vietnam_2014.nb

In[46]:=

Plot@Sinc@xD, 8x, 0, 10<, PlotStyle Thick,


ColorFunction HColorData@"TemperatureMap", 2D &LD

Out[46]=

Another useful color function that you can construct yourself is based on the function Blend
In[47]:=

? Blend
Blend@8col1 , col2 <, xD gives a color obtained by blending a fraction 1 - x of color col1 and x of color col2 .
Blend@8col1 , col2 , col3 , <, xD linearly interpolates between colors coli as x varies from 0 to 1.
Blend@88x1 , col1 <, 8x2 , col2 <, <, xD interpolates to give coli when x = xi .
Blend@8col1 , col2 , <, 8u1 , u2 , <D blends all the coli , using fraction ui of color coli .
Blend@8col1 , col2 , <D blends equal fractions of all the coli .

In[48]:=

Out[48]=

Plot@Sinc@xD, 8x, 0, 10<, PlotStyle Thick,


ColorFunction HBlend@8Red, Blue<, 1D &LD

ECM6Lecture8Vietnam_2014.nb

23

Frame Related Options


Overview
The next set of options that we will illustrate are those associated with frames. They are Frame,
FrameStyle, FrameTicks, and FrameLabel.
The default value for Frame is False. Setting Frame->True allows the other Frame options to be
visible. We start off with Frame -> True and FrameStyle -> Hue[.8]
In[49]:=

Plot@8Sin@xD, Cos@xD<, 8x, 0, 3 p<, Frame True, FrameStyle Directive@Hue@0.8DDD


1.0

0.5

Out[49]=

0.0

-0.5

-1.0
0

Directive Function
Note the use of the Function Directive:
In[50]:=

? Directive
Directive@g1 , g2 , D represents a single graphics directive composed of the directives g1 , g2 , .

This allows one to apply a whole series of graphic features as we illustrate below, where we apply
different directives for different sides of the Frame

FrameStyle
We can apply FrameStyle directives to the individual sides of the Frame. Here is an example using two
different colors.

24

ECM6Lecture8Vietnam_2014.nb

In[51]:=

Plot@8Sin@xD, Cos@xD<, 8x, 0, 3 p<, Frame True,


FrameStyle 88Directive@8Thick, Hue@0.8D<D, Directive@8Thin, Hue@0.6D<D<,
8Directive@Hue@0.2DD, Directive@8Thick, Hue@0.2D<D<<D
1.0

0.5

Out[51]=

0.0

-0.5

-1.0
0

The option FrameTicks allows one to specify the tick marks on the frame. Note that FrameTicks->True
is the default value. The syntax for individual ticks is FrameTicks-> 98x1 , x2 , ..<, 9y1, y2 , ..==. Here is
an example
In[52]:=

Plot@8Sin@xD, Cos@xD<, 8x, 0, 3 p<,


Frame True, FrameTicks 880, p, 2 p, 3 p<, 8- 1, 0, 1<<D
0

Out[52]=

2p

3p

-1

-1
0

2p

3p

The option FrameLabel allows one to place labels on the frames. Here we discuss the simplest option
with the syntax FrameLabel -> {xlabel, ylabel}, where the arguments are strings enclosed in quotes,
i.e., "text" . To ensure that the label on the vertical axis is horizontal we use the option RotateLabel ->
False

ECM6Lecture8Vietnam_2014.nb

In[53]:=

Plot@8Sin@xD, Cos@xD<, 8x, 0, 3 p<,


Frame True, FrameLabel 8"x-coordinate", "Sin@xD"<D
1.0

Out[53]=

Sin@xD

0.5

0.0

-0.5

-1.0
0

x-coordinate

We can also use the Style function to annotate the labels:


In[54]:=

? Style
Style@expr, optionsD displays with expr formatted using the specified option settings.
Style@expr, "style"D uses the option settings for the specified style in the current notebook.
Style@expr, colorD displays using the specified color.
Style@expr, BoldD displays with fonts made bold.
Style@expr, ItalicD displays with fonts made italic.
Style@expr, UnderlinedD displays with fonts underlined.
Style@expr, LargerD displays with fonts made larger.
Style@expr, SmallerD displays with fonts made smaller.
Style@expr, nD displays with font size n.
Style@expr, TinyD, Style@expr, SmallD, etc. display with fonts that are tiny, small, etc.

In[55]:=

Plot@8Sin@xD, Cos@xD<, 8x, 0, 3 p<, Frame True,


FrameLabel 8Style@"x-coordinate", 16, ItalicD, Style@"Sin@xD", 14, RedD<D
1.0

Out[55]=

Sin@xD

0.5

0.0

-0.5

-1.0
0

x-coordinate

25

26

ECM6Lecture8Vietnam_2014.nb

Using the Show Function


In some application it is desirable to suppress the display of a plot in the front end. In Mathematica 6
and later we simply use the ";" command. This is useful when we need to display several different
types of plots on the same set of axes, but do not want to show individual plots. Consider the following
example:
In[56]:=

myPlot1 = Plot@Sin@xD ^ 2, 8x, 0, 3 Pi<D;

There is no output. We can always display a graphics object with the command Show.
In[57]:=

Show@myPlot1D
1.0

0.8

0.6
Out[57]=

0.4

0.2

If we have more than one Graphics object, we can use Show to display them on the same axes, as
illustrated in the following example:
In[58]:=

myPlot2 = Plot@Sin@xD, 8x, 0, 3 p<D;


Show@myPlot1, myPlot2D
1.0

0.8

0.6
Out[59]=

0.4

0.2

Note that the Show command does not have any inherent options associated with the function

Overiding Options with Show


However, you can specify options in Show that override many but not all existing options in the graphic
object. Consider the following

ECM6Lecture8Vietnam_2014.nb

27

However, you can specify options in Show that override many but not all existing options in the graphic
object. Consider the following
In[60]:=

myPlot3 = Plot@Sin@xD, 8x, 0, 3 p<, AxesLabel 8"x", "Sin@xD"<D


Show@myPlot3, AxesLabel 8"x", "Sin@xD"<D
Sin@xD
1.0

0.5

Out[60]=

x
2

-0.5

-1.0
Sin@xD
1.0

0.5

Out[61]=

-0.5

-1.0

Options changes that require the graphic object to be re-evaluated cannot be changed. Consider the
PlotStyle option. This option cannot be used in Show as seen below

28

ECM6Lecture8Vietnam_2014.nb

In[62]:=

myPlot3 = Plot@Sin@xD, 8x, 0, 3 p<, PlotStyle Thickness@0.01`DD


Show@myPlot3, PlotStyle Thickness@0.02`DD
1.0

0.5

Out[62]=

-0.5

-1.0
1.0

0.5

Out[63]=

-0.5

-1.0

Other plot options that cannot be used in Show are PlotPoints, MaxBend, PlotDivision, Compiled.

ECM6Lecture8Vietnam_2014.nb

29

Adding Text to a Graphic


In this section we revisit the use of PlotLabel, AxesLabel, options and then consider the Epilog option.
In the use of these options we will examine how to incorporate text into graphics. The first option we
will consider is PlotLabel.

PlotLabel
The simplest syntax for this option is PlotLabel->This is a Trial Plot
In[64]:=

Plot@Sin@xD, 8x, 0, 3 p<, PlotLabel "This is a Trial Plot "D


This is a Trial Plot
1.0

0.5

Out[64]=

-0.5

-1.0

The string designated between the "text " is plotted with the default font for the graphic. If we want to
add to the properties of the text (i.e. embellish the text) we use the wrapper Style[exp, options], where
exp is the string we want to print. The options for Style include FontSize, FontWeight, FontSlant, FontFam
ily, FontColor and Background. Let us experiment with a few of these options. In this example, we specify
some font properties

30

ECM6Lecture8Vietnam_2014.nb

In[65]:=

PlotASin@xD2 , 8x, 0, 3 p<, PlotLabel StyleA"This is a plot of Sin@xD2 ",


FontFamily "Helvetica-Bold", FontSize 20, FontColor Hue@0.2DEE

This is a plot of Sin@xD2


1.0

0.8

0.6
Out[65]=

0.4

0.2

AxesLabel
We can use the same procedure to specify the attributes for the option AxesLabel which we saw earlier
has the syntax: AxesLabel->"ylabel", or AxesLabel-> {"xlabel","ylabel"}. In the following example
we illustrate how the StyleForm wrapper can be used to provide attributes to the individual labels
In[66]:=

PlotASin@xD2 , 8x, 0, 3 p<,


AxesLabel 8Style@"The x-coord", FontFamily "Helvetica-Bold",
FontSize 10, FontColor Hue@0.7`DD, Style@"The y-coord",
FontFamily "Courier", FontSize 15, FontColor Lighter@PurpleDD<E

The y-coord
1.0
0.8

Out[66]=

0.6
0.4
0.2

The x-coord

FrameTicks
The option Ticks allows one to modify the ticks on various axes. The default value is Ticks>Automatic. In this example we show how to modify ticks following the format used in FrameTicks
discussed earlier. The basic syntax is Ticks -> 88x1 , x2 , <, 8y1 , y2 ,<<. Note: if you want to
modify the ticks on one set of axes (say the x-axis), then the syntax is
Ticks -> 88x1 , x2 , ..<, Automatic<. We illustrate this below

ECM6Lecture8Vietnam_2014.nb

In[67]:=

31

Plot@Sin@xD, 8x, 0, 3 p<, Ticks 8Automatic, 8- 1, 0, 1<<D


1

Out[67]=

-1

We can also replace tick marks with other specifications. In this example we replace several tick marks
on the x-axis with String representations. The syntax for this is Ticks-> {{{2,"Two"},{4,"Four"}},
Automatic}
In[68]:=

Plot@Sin@xD, 8x, 0, 3 p<, Ticks 8882, "Two"<, 84, "Four"<, 86, "Six"<<, Automatic<D
1.0

0.5

Out[68]=

Two

Four

Six

-0.5

-1.0

Finally, we can wrap the String in the above example with Style and then use all the attributes of Style
In[69]:=

Plot@Sin@xD, 8x, 0, 3 p<,


Ticks 8882, Style@"Two", FontColor Hue@0.7`D, FontSize 25D<<, Automatic<D
1.0

0.5

Out[69]=

Two
-0.5

-1.0

In the previous examples we manipulated the attributes of the text associated with labels of ticks using
the wrapper Style.

32

ECM6Lecture8Vietnam_2014.nb

In the previous examples we manipulated the attributes of the text associated with labels of ticks using
the wrapper Style.

BaseStyle
We can also specify the attributes for the entire graphic. This is done with the plot option BaseStyle.
The syntax for BaseStyle is similar to Style.
In[70]:=

? BaseStyle
BaseStyle is an option for formatting and related constructs that specifies the base style to use for them.

In the following example we illustrate the use. Note that the syntax we are using is <.
BasetStyle -> 8option1 -> value1 , ..<.
In[71]:=

PlotASin@xD2 , 8x, 0, 3 p<,


AxesLabel 8"This is x-coord", "This is y-coord"<, BaseStyle
8FontFamily "Times-Bold", FontSize 12, FontColor RGBColor@0, 0.6`, 0.8`D<E
This is y-coord
1.0
0.8

Out[71]=

0.6
0.4
0.2
2

This is x-coord

The next topic we will discuss is the option Epilog which defines a set of graphic primitives that are
rendered after the main plot is rendered. Examples of graphic primitives are Text, Point, Rectangle,
etc. These are discussed in more detail in a future lecture. Let us consider first the syntax for the Text
primitive : Text[exp, coords], where exp is a string wrapped in " text", and coords are the coordinates
for the placement of the text

Epilog
Note that the argument for Epilog is a graphic Primitive or a list of graphic Primitives
In[72]:=

? Epilog
Epilog is an option for graphics functions that gives a list of
graphics primitives to be rendered after the main part of the graphics is rendered.

ECM6Lecture8Vietnam_2014.nb

In[73]:=

33

PlotASin@xD2 , 8x, 0, 3 p<, Epilog Text@"One fine day", 86, 0.4`<DE


1.0

0.8

0.6
Out[73]=

One fine day

0.4

0.2

In the above example we used Text as our graphic primitive. To add additional attributes to the Epilog
option, we can one again make use of Style as illustrated here
In[74]:=

PlotASin@xD2 , 8x, 0, 3 p<,


Epilog Text@Style@"One fine day", FontFamily "Helvetica-Bold",
FontSize 20, FontColor Hue@0.7`DD, 86, 0.4`<DE
1.0

0.8

0.6
Out[74]=

One fine day

0.4

0.2

34

ECM6Lecture8Vietnam_2014.nb

Other Plot Functions: ListPlot


ListPlot function
The function that is used to plot discrete data points is called ListPlot. In its simplest form the argument
of ListPlot is a list of y-values of the form 8y1 , y2 , y3 , .. yn }. To illustrate the features of ListPlot, we first
generate a data set by using the function Table (we have suppress the output by ending the input
command with a semi-colon):
In[75]:=

yvalues = Table@Sin@5 xD Exp@- x ^ 2D, 8x, - 3, 3, .02<D;

Next we use ListPlot to display the data. Each data point is assigned an x-values according to its index
in the list. For example, the x-value for the first data point is x=1, the last data point is x=300.
In[76]:=

ListPlot@yvaluesD
0.4

0.2

Out[76]=

50

100

150

200

250

300

-0.2

-0.4

The options available for ListPlot are very similar to Plot, though not identical

ECM6Lecture8Vietnam_2014.nb

In[77]:=

Out[77]=

35

Options@ListPlotD
:AlignmentPoint Center, AspectRatio

, Axes True,
GoldenRatio
AxesLabel None, AxesOrigin Automatic, AxesStyle 8<, Background None,
BaselinePosition Automatic, BaseStyle 8<, ClippingStyle None,
ColorFunction Automatic, ColorFunctionScaling True, ColorOutput Automatic,
ContentSelectable Automatic, CoordinatesToolOptions Automatic,
DataRange Automatic, DisplayFunction $DisplayFunction, Epilog 8<,
Filling None, FillingStyle Automatic, FormatType TraditionalForm,
Frame False, FrameLabel None, FrameStyle 8<, FrameTicks Automatic,
FrameTicksStyle 8<, GridLines None, GridLinesStyle 8<, ImageMargins 0.,
ImagePadding All, ImageSize Automatic, ImageSizeRaw Automatic,
InterpolationOrder None, Joined False, LabelStyle 8<, MaxPlotPoints ,
Mesh None, MeshFunctions 81 &<, MeshShading None, MeshStyle Automatic,
Method Automatic, PerformanceGoal $PerformanceGoal, PlotLabel None,
PlotLegends None, PlotMarkers None, PlotRange Automatic,
PlotRangeClipping True, PlotRangePadding Automatic, PlotRegion Automatic,
PlotStyle Automatic, PreserveImageOptions Automatic, Prolog 8<,
RotateLabel True, TargetUnits Automatic, Ticks Automatic, TicksStyle 8<>

It is apparent in the previous plot that not all the data points were displayed. This occurred because
some y-values were outside the default range of the y-axis. Thus we need to change the PlotRange
option. For our purposes we use the option PlotRange -> All, i.e.,
In[78]:=

ListPlot@yvalues, PlotRange AllD

0.5

Out[78]=

50

100

150

200

250

300

-0.5

If your data is in the form of {x, y} pairs you can still use ListPlot. The first argument of ListPlot should
be a list of a list. If we return to our earlier data, we can create a {x, y} pair using Table as follows:
In[79]:=

xyvalues = Table@8x, Sin@5 xD Exp@- x ^ 2D<, 8x, - 3, 3, .02<D;

Now ListPlot plots the data as a function of x

36

ECM6Lecture8Vietnam_2014.nb

In[80]:=

ListPlot@xyvalues, PlotRange AllD

0.5

Out[80]=

-3

-2

-1

-0.5

We can embellish our plot using the various ListPlot options as illustrated with the Plot function. For
example suppose we want to change the size of the data points and their color
In[81]:=

ListPlot@xyvalues, PlotRange All, PlotStyle 8Hue@0.9D, PointSize@0.015D<D

0.5

Out[81]=

-3

-2

-1

-0.5

Plotting x-y Data


Example 1:
If your data is in the form of {x, y} pairs you can still use ListPlot. The first argument of ListPlot should
be a list of a list. If we return to our earlier data, we can create a {x, y} pair using Table as follows:
In[82]:=

xyvalues = Table@8x, Sin@5 xD Exp@- x ^ 2D<, 8x, - 3, 3, .02<D;

Now ListPlot plots the data as a function of x

ECM6Lecture8Vietnam_2014.nb

In[83]:=

37

ListPlot@xyvalues, PlotRange AllD

0.5

Out[83]=

-3

-2

-1

-0.5

We can embellish our plot using the various ListPlot options as illustrated with the Plot function. For
example suppose we want to change the size of the data points and their color
In[84]:=

ListPlot@xyvalues, PlotRange All, PlotStyle 8Hue@0.9D, PointSize@0.015D<D

0.5

Out[84]=

-3

-2

-1

-0.5

Example 2:
Suppose you have a list 8y1 , y2 , , yn < and another list 8x1 , x2 , , xn <and you would like to use
ListPlot to plot the y-data versus x. Recall that ListPlot requires that the data be in the form
88x1 , y1 <, 8x2 , y2 <, , 8xn , yn <<
Hence we need to manipulate the two lists. This can be readily done with the Transpose function. First
we create a list of x values, using the previous range and spacing:
In[85]:=

xvalues = Table@x, 8x, - 3, 3, .02<D;

Now we use Transpose to create a list of (x-y) pairs


In[86]:=

myNewXYValues = Transpose@8xvalues, yvalues<D;

Here is the plot.

38

ECM6Lecture8Vietnam_2014.nb

In[87]:=

ListPlot@myNewXYValues, PlotRange AllD

0.5

Out[87]=

-3

-2

-1

-0.5

If you want to join the data points use the option Joined
In[88]:=

ListPlot@myNewXYValues, PlotRange All, Joined TrueD

0.5

Out[88]=

-3

-2

-1

-0.5

ECM6Lecture8Vietnam_2014.nb

Other Plot Functions: ParametricPlot


The ParametricPlot function allows one to plot parametric curves in two dimensions. The function is
specified as
In[89]:=

? ParametricPlot
ParametricPlotA9 fx , fy =, 8u, umin , umax <E generates a
parametric plot of a curve with x and y coordinates fx and fy as a function of u.
ParametricPlotA99 fx , fy =, 9gx , gy =, =, 8u, umin , umax <E plots several parametric curves.
ParametricPlotA9 fx , fy =, 8u, umin , umax <, 8v, vmin , vmax <E plots a parametric region.
ParametricPlotA99 fx , fy =, 9gx , gy =, =, 8u, umin , umax <, 8v, vmin , vmax <E plots several parametric regions.

The first argument is a list of the two functions, while the second argument specifies the range of the
parametric variable. In the following example we define functions f[t], g[t], and then graph the two
functions for t in the range 0 t 8p. Note that we have made the assignments immediate for the
reasons discussed earlier in the tutorial.
In[90]:=

myF@t_D = Sqrt@tD Cos@tD


myG@t_D = Sqrt@tD Sin@tD

Out[90]=

t Cos@tD

Out[91]=

t Sin@tD

In[92]:=

ParametricPlot@8myF@tD, myG@tD<, 8t, 0, 8 p<D

Out[92]=

-4

-2

-2

-4

If we change the aspect ratio for the plot changes accordingly.

39

40

ECM6Lecture8Vietnam_2014.nb

In[93]:=

ParametricPlot@8myF@tD, myG@tD<, 8t, 0, 8 p<, AspectRatio 0.7D


4

Out[93]=

-4

-2

-2

-4

ECM6Lecture8Vietnam_2014.nb

41

ContourPlot
Plotting Implicit Functions
In the previous examples the function that was plotted was an explicit function of the independent
variable, viz., y=f(x). When y is only known implicitly as a function of x , g(x,y)=0, then it is necessary to
use the routine ContourPlot.
We illustrate the use of ContourPlot with the following equation
In[94]:=

feqn@a_, b_D@x_, y_D := y2 Iy2 - b2 M - x2 Ix2 - a2 M == 0

We plot this equation for selected values of the parameters : a=3, b=3.2. Note that we must wrap
Evaluate around the implicit equation, feqn[a, b] [x, y], since we made a delayed assignment (see
above). For selected values of x the plot shows that our equation has 4 solutions!
The following example illustrates the method. In this example we also invoke some plot options
In[95]:=

ContourPlot@Evaluate@feqn@3, 3.2D@x, yDD, 8x, - 4, 4<,


8y, - 4, 4<, ContourStyle Directive@8Thick, Hue@0.8`D<DD
4

Out[95]=

-2

-4
-4

-2

42

ECM6Lecture8Vietnam_2014.nb

Application: Exploring the Plot Options


Mathematica's plotting routines use an adaptive sampling routine. Thus the number of points used by a
routine for plotting a function is not readily known. Equally important we do not know how Mathematica
sampled the function. In this example we will show how one can deduce this information using some
simple programing techniques. Consider the following plot
In[96]:=

myBesselPlot = Plot@BesselJ@1, xD, 8x, 0, 6 p<, PlotStyle BlueD


0.6

0.4

0.2
Out[96]=

10

15

-0.2

We can use the InputForm to see how this plot is constructed.


In[97]:=

Short@InputForm@myBesselPlotDD

Out[97]//Short=

Graphics@888<, 8<, 8Hue@0.67, 0.6, 0.6D, << 1 >>, Line@8<< 901 >><D<<<, 8<< 8 >><D

We see it is a Graphics object that uses the Line primitive. The syntax for the line primitive is
Line@88x1 , y1 <, 8x2 , y2 <, , 8xn , yn <<D

Thus a straight line is drawn from each data pair. This means that the xi values denote the sampling
locations used in Plot. It will be convenient to extract all the data from the Line primitive. We can do
this with the Cases function. This function allows you to search a Mathematica expression using a
specified pattern. For our purposes we will use the following pattern: Line@8x__<D -> x. What this
pattern does is extract the Line primitive and then replace the argument of the Line primitive which is
the actual coordinate data, with the data itself. Recall the BlankSequence (double underscore) in the
pattern matches with one or more Mathematica expressions. In our case this would be the list of data
pairs. Let us apply the Cases function to our graphics object (The third argument in Cases specifies the
Level to do the pattern matching. By specifying Infinity, Cases we search at all levels of the
expression.)
In[98]:=

Cases@myBesselPlot, Line@8x__<D x, D

Our next task is to take the list of data pairs and construct a new set of line primitives for each of the
data pairs with the following form:
Line@88xi , yi <, 8xi , 0<<D
When wrapped with Graphics this line primitive will be a vertical line at xi with height yi . We can
readily construct these Line primitives using the Map function

Our next task is to take the list of data pairs and construct a new set of line primitives for each of the
ECM6Lecture8Vietnam_2014.nb
data pairs with the following form:
Line@88xi , yi <, 8xi , 0<<D
When wrapped with Graphics this line primitive will be a vertical line at xi with height yi . We can
readily construct these Line primitives using the Map function
In[99]:=

43

Map@Line@8, 8First@D, 0<<D &, Cases@myBesselPlot, Line@8x__<D x, DD


A very large output was generated. Here is a sample of it:

Out[99]=

8Line@883.84685 10-7 , 1.92342 10-7 <, 83.84685 10-7 , 0<<D,


Line@880.0057815, 0.00289074<, 80.0057815, 0<<D,
897, Line@8818.8431, - 0.128285<, 818.8431, 0<<D,
Line@8818.8496, - 0.127409<, 818.8496, 0<<D<
Show Less

Show More

Show Full Output

Set Size Limit...

Finally, we can wrap this list with Graphics to create our graphics object
In[100]:=

mySamplePoints =
Graphics@Map@Line@8, 8First@D, 0<<D &, Cases@myBesselPlot, Line@8x__<D x, DDD

Out[100]=

We can display our Graphics object using Show, and for convenience we will overlay it with our original plot .
In[101]:=

Show@myBesselPlot, mySamplePointsD
0.6

0.4

0.2
Out[101]=

10

15

-0.2

With this function we can examine how Mathematica responds to certain changes in the plot options

44

ECM6Lecture8Vietnam_2014.nb

In[102]:=

Out[102]=

Options@PlotD
:AlignmentPoint Center, AspectRatio

, Axes True,
GoldenRatio
AxesLabel None, AxesOrigin Automatic, AxesStyle 8<, Background None,
BaselinePosition Automatic, BaseStyle 8<, ClippingStyle None,
ColorFunction Automatic, ColorFunctionScaling True, ColorOutput Automatic,
ContentSelectable Automatic, CoordinatesToolOptions Automatic,
DisplayFunction $DisplayFunction, Epilog 8<, Evaluated Automatic,
EvaluationMonitor None, Exclusions Automatic, ExclusionsStyle None,
Filling None, FillingStyle Automatic, FormatType TraditionalForm,
Frame False, FrameLabel None, FrameStyle 8<, FrameTicks Automatic,
FrameTicksStyle 8<, GridLines None, GridLinesStyle 8<,
ImageMargins 0., ImagePadding All, ImageSize Automatic,
ImageSizeRaw Automatic, LabelStyle 8<, MaxRecursion Automatic,
Mesh None, MeshFunctions 81 &<, MeshShading None, MeshStyle Automatic,
Method Automatic, PerformanceGoal $PerformanceGoal, PlotLabel None,
PlotLegends None, PlotPoints Automatic, PlotRange 8Full, Automatic<,
PlotRangeClipping True, PlotRangePadding Automatic, PlotRegion Automatic,
PlotStyle Automatic, PreserveImageOptions Automatic, Prolog 8<,
RegionFunction HTrue &L, RotateLabel True, TargetUnits Automatic,
Ticks Automatic, TicksStyle 8<, WorkingPrecision MachinePrecision>

Our goal now is to see what happens when we change PlotPoints and MaxRecursion :First here is what
the plot looks like when we change these options.
In[103]:=

myBesselPlot2 = Plot@BesselJ@1, xD, 8x, 0, 6 p<,


PlotStyle RGBColor@0, 0, 1D, PlotPoints 10, MaxRecursion 2D

0.4

0.2
Out[103]=

10

15

-0.2

Now let us extract the data from the plot and create a graphics primitive with the appropriate sample
lines
In[104]:=

mySamplePoints2 =
Graphics@Map@Line@8, 8First@D, 0<<D &, Cases@myBesselPlot2, Line@8x__<D x, DDD

Out[104]=

Let's use Show to see visually what is happening:

ECM6Lecture8Vietnam_2014.nb

In[105]:=

Show@myBesselPlot2, mySamplePoints2D

0.4

0.2
Out[105]=

-0.2

10

15

45

You might also like