This notebook is part of a draft of a set of elementary Mathematica tutorials, as presented at the 1999 Mathematica Developer Conference, October 20-23, 1999. This draft is provided here to encourage suggestions about these tutorials. You can send suggestions about these tutorials to Wolfram Research Technical Support at the address support@wolfram.com.

Only the first nine parts of the Basic Tutorial are included in this draft.

Basic Tutorial (part 4 of 10)

4 Plotting and Graphics

In this fourth part of the basic tutorial you will learn about:

• Making plots of functions
• Making plots of data
• Axes and labels
• Working with graphical elements

Making plots of functions

A few simple examples can be used to illustrate the basic characteristics of functions such as Plot and Plot3D that are available in Mathematica for plotting numerical functions.

Here is an example showing the use of the Plot function to plot Sin[x] for x ranging from 0 to 6  Pi.

Plot[Sin[x], {x, 0, 6  Pi}]

The Plot function works by evaluating the first argument at points in the range specified by the second argument, and connecting those points with straight lines. In most cases the straight line segments are so short that plot looks like a smooth curve. The expression returned by Plot is a Graphics expression, shown in the output as ⁃Graphics⁃. The image itself is generated as a side effect.

The vertical range of the plot is chosen automatically using built-in heuristics. If you would like to see a vertical range other than the range that is chosen automatically, you can use the PlotRange option to specify the vertical range explicitly. For example:

Plot[Sin[x], {x, 0, 6  Pi}, PlotRange -> {0, 1}]

Here is an example showing the use of the Plot3D function to plot Sin[x] for x ranging from 0 to 6  Pi. The result from Plot3D is a SurfaceGraphics expression, shown in the output as ⁃SurfaceGraphics⁃.

Plot3D[x Cos[Pi y], {x, -1, 1}, {y, 0, 2}]

Just as the Plot function works by evaluating the first argument at a set of points and connecting those points with straight lines, the Plot3D function works by evaluating the first argument on a grid of points and drawing plane surfaces between those points. The second and third arguments in Plot3D give the variables and the ranges of those variables.

Also, as with Plot, the Plot3D function accepts many options that allow you to control various characteristics of the plot. Here is an example in which the AxesLabel option is used to label two of the axes, the Mesh option is used to omit the grid lines on the surface, and the ViewPoint option is used to change the point from which the image is viewed.

Plot3D[x Cos[Pi y], {x, -1, 1}, {y, 0, 2}, 
      AxesLabel -> {"x", "y", None}, Mesh -> False, 
      ViewPoint -> {2, -1, 2}]

In addition to Plot and Plot3D, the other built-in functions for making plots of numerical functions are ContourPlot, DensityPlot, ParametricPlot, and ParametricPlot3D. All of these functions use similar syntax, and have many similar characteristics. For information and examples, see the documentation for each function.

Making plots of data

For every function that is available for plotting numerical functions, there is an analogous function for plotting data. Here is an example showing the use of the ListPlot function to plot a list of points. The PlotJoined option is included to cause lines to be drawn between the points in the data.

data = {{3, 1.5}, {17, 0.3}, {31, 0.5}, {45, 0.1}, {60, 2.7}, {70, 
            3.2}, {75, 3.3}, {85, 3.3}, {100, 4.0}};

ListPlot[data, PlotJoined -> True]

The ListPlot function is typical of functions used for plotting data. The other built-in functions for plotting data are ListPlot3D, ListContourPlot, ListDensityPlot., all of which are used for plotting data arrays rather than lists of data points.

As an example, here is a contour plot of a data array generated using Table. The MeshRange option is used here to specify the range of the independent coordinates (the values of x and y). Without this specification the axes would be labeled to show a range 1 through 9 in the vertical direction and 1 through 5 in the horizontal direction, since the data are given as a 9 by 5 array. To see this effect, try the same example without the MeshRange option.

data = 
        Table[Sqrt[x^2 + y^2], {y, 0, 80, 10.0}, {x, 0, 60, 
            15.0}];

ListContourPlot[data, MeshRange -> {{0, 60}, {0, 80}}]

It is instructive to compare this plot with the original data. Note that the first row in the data array corresponds to the bottom of the plot.

Graphics

MatrixForm[data]

Standard plotting packages

The standard packages that are included with Mathematica contain many other functions for constructing plots and other graphical images. You can make these functions available in Mathematica by using Get or Needs to load individual packages, or by evaluating << Graphics` (or Get["Graphics`"]) to set up automatic loading of all of the graphics packages.

<< Graphics`

Among the functions defined in these packages are functions for making plots on various logarithmic scales. Here is an example showing the use of the LogPlot function to make a plot in which the vertical scale is logarithmic. The LogPlot function is defined in the Graphics`Graphics` package, which includes many other functions for making common types of plots.

LogPlot[Exp[x^2]/(1 + x^2), {x, 0, 4}]

Another function from the Graphics`Graphics` package is BarChart, which can be used for making bar charts. Here is an example showing the use of the BarChart function.

BarChart[{2, 1, 4, 4, 6, 7, 9, 11, 10, 7, 3, 2, 2, 3, 2, 1}]

For more information see the notes on Graphics and Geometry Packages in the Add-Ons section of the Help Browser, or the documentation for individual packages.

Axes and labels

The variety of methods for adding labels to plots is of course endless. Many of the more common ways of adding labels to plots can be handled through options of plotting functions.

Here is an example showing the default behavior of Plot in plotting a pair of functions.

Plot[{Sin[x], Cos[x]}, {x, 0, 3  Pi}]

Here is a plot of the same pair of functions but with several non-default option settings to control the labels on the plot.

Plot[{Sin[x], Cos[x]}, {x, 0, 3  Pi}, 
      PlotLabel -> "Cos[x] and Sin[x]", Frame -> True, 
      FrameLabel -> {x, y}, PlotStyle -> {Dashing[{0.02}], {}}, 
      FrameTicks -> {{{0, 0}, {Pi, Pi}, {2  Pi, 2  Pi}, {3  Pi, 3  Pi}}, 
          Automatic, None, None}]

The PlotLabel option is used to add a title across the top of the plot.

The setting Frame->True for the Frame option adds a frame to the plot, rather than axes.

The FrameLabel option adds labels to the frame. The setting FrameLabel->{x,y} adds x as the label for the bottom of the frame and y as the label for the left side of the frame.

The PlotStyle option specifies the style of the lines in the plot. The value {Dashing[{0.02}],{}} for the PlotStyle option specifies that the first line should be drawn dashed and the second line should be drawn as a solid line (the default style). If the plot contains many lines, different arguments in the Dashing directive, or other style specifications, such as color and thickness can be used to distinguish the lines. Graphics directives are discussed in the next section of this tutorial.

The FrameTicks option specifies how tick marks should be arranged and labeled around the frame. In this example the value of the FrameTicks option is a list with four elements. The first element is a list that specifies the positions and labels for individual tick marks along the bottom of the frame. The second element is the symbol Automatic, which indicates that default tick marks and labels should be used on the left side of the frame. The last two elements are None, which indicates that no tick marks should be shown along the right side of the frame or along the top of the frame.

You can see all of the options of the Plot function by evaluating Options[Plot]. Many of these options are used for controlling axes and labels. You can get more information about the use of these options by looking them up in the Help Browser.

Graphical elements

All of the points, lines, text, color instructions, and other elements that are used to construct graphical images are represented in Mathematica using expressions. These expressions are used in results from Plot and other plotting functions. In many situations, however, it is helpful or necessary to work with these expressions directly.

Expressions that describe geometrical elements such as points and lines are called graphics primitives. For example, the expression Line[{{1,1},{2,2}}] is a two-dimensional graphics primitive that specifies a line from the point {1,1} to the point {2,2}.

Expressions that specify color, dashing, line thickness, and other characteristics of geometrical elements are called graphics directives. The graphics directive Dashing[{0.02}], which was encountered in the previous section, specifies that subsequent lines should be dashed with dash segments that have length 0.02 of the width of the plot.

Many characteristics of graphical images can be controlled using graphics options. A number of graphics options have already been encountered in previous sections this tutorial. For example, the option Frame->True in two-dimensional graphics specifies that a frame should be drawn around the plot.

Graphics primitives, graphics directives, and graphics options are collected into graphics expressions. For example, the expressions with a head of Graphics that are returned by Plot are graphics expressions. Other common graphics expressions include expressions with a head of SurfaceGraphics (such as the expressions returned by Plot3D) or ContourGraphics (such as the expressions returned by ContourPlot).

The first argument in Graphics is a list of graphics primitives and graphics directives. Here is an example of a graphics expression with a head of Graphics and with a single Line primitive listed in the first argument. The Line primitive in this example represents a line from the point {1,3} to the point {2,2} to the point {3,5} to the point {4,4} to the point {5,7}. The result is formatted by default as ⁃Graphics⁃.

g = 
      Graphics[{Line[{{1, 3}, {2, 2}, {3, 5}, {4, 4}, {5, 7}}]}]

You can use the Show function to display the image represented by this graphics expression. The use of the Line primitive in this example is typical the way that Line is used in the output of Plot and ListPlot.

Show[g]

Here is a more complicated graphics expression demonstrating the use of Line, Point, Text, and Polygon graphics primitives, Thickness, PointSize, and RGBColor graphics directives, and several graphics options. A useful way to learn about graphics expressions is to try various changes to examples such as this one and to observe the effect of your changes on the image that is displayed.

Show[
      Graphics[{Line[{{1, 1}, {4, 2}}], 
Thickness[0.02], 
          Line[{{1, 4}, {4, 4}}], 
RGBColor[1, 0, 
            0], 
PointSize[0.05], 
          Point[{4, 
              1}], 
Polygon[{{1, 2}, {3, 3}, {1, 
                3}}], 
Text[
            StyleForm["Red triangle", FontSize -> 12], {2, 3.2}, 
            Background -> 
              GrayLevel[1]], 
Line[{{2, 1}, {2, 2}, {3, 
                1}, {3, 2}}]}, Background -> GrayLevel[0.8], 
        AspectRatio -> 1, Axes -> True, 
        PlotRange -> {{0, 5}, {0, 5}}]]

Exercises

Exercise 4.1 Plotting a table of functions

Correct the error in this input by enclosing the first argument of Plot in Evaluate. The result should be a plot of Sin[n x] for five integer values of n.

Plot[Table[Sin[n x], {n, 1, 5}], {x, 0, 1}]

The original example fails because the Plot function holds the first argument unevaluated until numerical values are inserted for the variable. Since the first argument is not explicitly a list, Plot expects the first argument to evaluate to a number. The calculation fails when the first argument instead evaluates to a list of numbers.

This failure can be addressed in a variety of ways, one of which is to enclose the first argument of Plot in Evaluate to force evaluation of the table.

Exercise 4.2 Plotting data

Here is an list of pairs of numbers representing data collecting in an experiment. Use ListPlot to plot these data as a set of points. Assign the result as the value of a variable dataplot for use in the next exercise.

{{1.030, 0.021}, {1.087, 0.026}, {1.176, 0.036}, {1.409, 
        0.080}, {1.470, 0.096}, {1.549, 0.122}, {1.586, 0.135}, {1.684, 
        0.177}, {1.926, 0.315}, {1.997, 0.366}, {2.11`, 0.453}, {2.171, 
        0.503}, {2.183, 0.513}, {2.209, 0.535}, {2.266, 0.584}, {2.366, 
        0.669}, {2.457, 0.745}, {2.467, 0.753}, {2.547, 0.814}, {2.774, 
        0.950}, {2.852, 0.978}, {2.896, 0.989}, {3.043, 0.998}, {3.064, 
        0.996}, {3.223, 0.954}, {3.467, 0.862}, {3.711, 1.037}, {3.718, 
        1.049}, {3.785, 1.170}, {3.837, 1.264}, {4.006, 1.363}, {4.093, 
        1.221}, {4.131, 1.119}, {4.227, 0.820}, {4.255, 0.728}, {4.257, 
        0.724}, {4.402, 0.339}, {4.912, 0.026}, {5.067, 0.014}, {5.104, 
        0.012}, {5.168, 0.009}, {5.287, 0.005}, {5.453, 0.002}, {5.455, 
        0.002}, {5.458, 0.002}, {5.597, 0.001}, {5.695, 0.001}, {5.717, 
        0.001}, {5.723, 0.001}, {5.874, 0.000}}

Exercise 4.3 Combining plots

Here is a plot representing a theoretical fit to the data in the previous exercise.

fitplot = Plot[1.3  Exp[-(x - 3.4)^2], {x, 0, 6}]

Use Show to combine this plot with plot from the previous exercise. For information regarding this use of Show, enter ?Show, or see the documentation for Show. For additional information see Section 1.9.4 in The Mathematica Book.

Exercise 4.4 Controlling tick marks on a plot

Recall the example in which the FrameTicks option was used to specify explicit positions and labels for the tick marks across the bottom of the frame around a plot:

Plot[{Sin[x], Cos[x]}, {x, 0, 3  Pi}, 
      PlotLabel -> "Cos[x] and Sin[x]", Frame -> True, 
      FrameLabel -> {x, y}, PlotStyle -> {Dashing[{0.02}], {}}, 
      FrameTicks -> {{{0, 0}, {Pi, Pi}, {2  Pi, 2  Pi}, {3  Pi, 3  Pi}}, 
          Automatic, None, None}]

An explicit tick specification such as {{0,0},{Pi,Pi},{2Pi,2Pi},{3Pi,3Pi}} provides for precise control over the tick marks on a plot, but entering such a specification can be a relatively time-consuming and error-prone task. The tick specification in this and many similar examples can also be generated using the PiScale or UnitScale functions, both of which are defined in the Graphics`Graphics` package. Here is an example showing the use of the UnitScale function to generate tick marks and tick labels at 0, Pi, 2 Pi, and 3 Pi.

Plot[{Sin[x], Cos[x]}, {x, 0, 3  Pi}, 
      PlotLabel -> "Cos[x] and Sin[x]", Frame -> True, 
      FrameLabel -> {x, y}, PlotStyle -> {Dashing[{0.02}], {}}, 
      FrameTicks -> {UnitScale[0, 3  Pi, Pi], Automatic, None, 
          None}]

Here is another plot. Add a value for the Ticks option to give tick marks and tick labels at multiples of 60 along the horizontal axis. The result should be a plot with a tick mark and tick label at 60, 120, 180, 240, 300, 360, 420, and 480. You can do this either using UnitScale[0,500,60], or by including a list specifying the position and label for each tick mark in the value of the Ticks option.

Plot[Exp[-((x - 100)/100)^2], {x, 0, 500}]

Although not part of this exercise, it is worth noting that other functions for generating tick specifications are also available. One of the more frequently used functions is LogScale, which generates tick specifications for logarithmic scales. Here is an example showing the use of LogScale to add a logarithmic scale to the right side of the frame around a plot.

Plot[{x, 1 + Sqrt[x]}, {x, 0, 4}, Frame -> True, 
      FrameTicks -> {Automatic, Automatic, None, LogScale}]

Exercise 4.5 Labeling elements in a plot

Here is an example showing the use of the Epilog option of Plot and the Text and Arrow graphics primitives to label a point on a curve. The Arrow primitive is defined in the Graphics`Arrow` package.

<< Graphics`

Plot[8 - x^3 + 4  x^2 + 3  x, {x, -3, 5}, 
      Epilog -> {Arrow[{2, 40}, {3, 26}], 
          Text["local maximum", {2, 45}]}]

Replace the Arrow primitive in this example with a corresponding Line primitive so that a line rather than an arrow is drawn between the text and the curve. The finished plot should look like this:

Exercise 4.6 Controlling the axes in a plot

Set the value of the AxesOrigin option in this example so the axes cross at the point {2 Pi, -1}, and set the AxesStyle option to RGBColor[0,0,1] so the axes are drawn in blue.

Plot[Cos[x], {x, 0, 4  Pi}]

Exercise 4.7 Drawing a histogram

Add an option to the Histogram function in this example so that the plot shows 9 bars (categories), rather than the default number of categories.

The Histogram function is defined in the Graphics`Graphics` package. The BarStyle option is set in this example so that the histogram is displayed using alternate gray and blue bars.

<< Graphics`Graphics`

data = N[Table[Cos[k], {k, 500}]];

Histogram[data, 
      BarStyle -> {GrayLevel[0.5], RGBColor[0, 0, 1]}]

Exercise 4.8 Combining two surfaces

Use Show to combine the two surfaces shown here.

The first surface is a spiral constructed using ParametricPlot3D.

g1 = 
      ParametricPlot3D[{y Cos[Pi x], y Sin[Pi x], x},  {x, 0, 
          2}, {y, -1, 1}]

The second surface is based on plane generated using Plot3D. The PlotPoints option is used to specify the number of grid points to use in each direction in generating this surface. Applying the WireFrame function to the result replaces each polygon in this surface by an outline of the polygon. The image displayed here is drawn before the WireFrame function is applied, and so shows the complete polygons. The wireframe image will be displayed when Show is applied to the result. The wireframe image provides a form of transparency.

g2 = 
      WireFrame[
        Plot3D[1 + y, {x, -1, 1}, {y, -1, 1}, 
          PlotPoints -> 50]]

Exercise 4.9 Plotting several data sets

Here is an example showing the use of MultipleListPlot to plot two data sets on the same plot. The MultipleListPlot function is defined in the standard Graphics`MultipleListPlot` package.

data1 = {{0.16, 0.18}, {1.20, 0.73}, {1.43, 0.85}, {1.72, 
            0.96}, {2.57, 0.85}, {3.20, 0.63}, {3.27, 0.65}, {3.83, 
            1.10}, {3.95, 1.14}, {4.21, 0.96}, {4.28, 0.86}, {4.71, 
            0.25}, {5.00, 0.06}, {5.31, 0.01}, {5.64, 0.01}};

data2 = {{0.26, 0.22}, {0.49, 0.28}, {0.89, 0.41}, {1.66, 
            0.70}, {1.99, 0.82}, {2.36, 0.92}, {2.81, 0.99}, {3.30, 
            0.98}, {3.65, 0.92}, {5.27, 0.36}};

MultipleListPlot[data1, data2, 
      SymbolShape -> {PlotSymbol[Box], 
          MakeSymbol[{Line[{{0, -3}, {0, 3}}], 
              Line[{{-3, 0}, {3, 0}}]}]}]

Here is a third data set, assigned as the value of data3.

data3 = {{0.181, 0.497}, {0.385, 0.456}, {0.842, 0.807}, {1.890, 
            0.955}, {2.646, 1.234}, {3.016, 1.266}, {3.419, 0.897}, {3.454, 
            0.969}, {4.591, 0.848}, {5.078, 0.526}, {5.599, 
            0.594}};

Change the MultipleListPlot input above to include data3 and change the value of the SymbolShape option so that a different plot symbol of your choice is used for the points in data3. Here are some of the symbols that you might consider:

({{Point, point}, {PlotSymbol[Triangle], small filled triangle}, {PlotSymbol[Triangle, 4], larger filled triangle}, {PlotSymbol[Diamond, 4], filled diamond shape}, {MakeSymbol[RegularPolygon[4, 4]], empty diamond shape}, {MakeSymbol[RegularPolygon[4, 4, 0, Pi/4]], empty square}})

Exercise 4.10 Adding a legend to a plot

Add a legend identifying the plot symbols in the plot from the previous exercise.

A legend can be added to the example plot by including PlotLegend->{"data1","data2"} as an option to MultipleListPlot. The MultipleListPlot function includes several options relating to legends. You can add a legend to any plot using the functions in the Graphics`Legend` package or by constructing a legend using graphics primitives.