Mathematica Graphics 2D Commands


This document primarily covers information about 2D graphics commands in Mathematica. You may also be interested in Mathematica Commands or Mathematica 3D Graphics.

TABLE OF CONTENTS

Animation

If you draw a sequence of plots, you can have Mathematica animate them, that is, display them one after another, as though they were individual frames of a movie.

To make an animation, you must first generate a sequence of plots, using any of the usual graphics commands, such as ListPlot, ParametricPlot or Plot.

You should try to make sure that each frame or plot has the same shape (what Mathematica calls the AspectRatio, and uses the same x and y intervals, (which you can control with the option PlotRange.

Here is a very simple set of frames that show how the shape of the function y=a*x^3+x+1 will change as the coefficient a is varied:


        Clear[a,f,p0,p1,p2,p3,p4,p5,x]

        f[x_] := a*x^3+x+1

        a = 0;
        p0 = Plot[f[x], {x,-2,2}, PlotRange->{-2,4}]

        a = 1;
        p1 = Plot[f[x], {x,-2,2}, PlotRange->{-2,4}]

        a = 2;
        p2 = Plot[f[x], {x,-2,2}, PlotRange->{-2,4}]

        a = 3;
        p3 = Plot[f[x], {x,-2,2}, PlotRange->{-2,4}]

        a = 4;
        p4 = Plot[f[x], {x,-2,2}, PlotRange->{-2,4}]

        a = 5;
        p5 = Plot[f[x], {x,-2,2}, PlotRange->{-2,4}]
      

If you are not using a notebook interface, it is possible that you can animate these plots using the command:


        ShowAnimation[{p0,p1,p2,p3,p4,p5}]
      

In the notebook interface, we "select" the frames to be animated - that is, we place the cursor near the bracket on the right margin of the first plot and click once. Now hold down the shift key, and click in the right hand brackets of all the other plots you want to include in the animation.

Now go to the Graph menu and select Animate Selected Graphics. This should cause a brief animation of your plots to be displayed. It will probably be over too quickly for you to enjoy. In that case, go back to the Graph menu and select Animation. This will give you a menu that will allow you to specify how many frames per second should be displayed, and whether the animation should loop forward only, or forward and back again. A little experimentation should make a pleasing display.

Back to TABLE OF CONTENTS.

AspectRatio

AspectRatio is an option that may be specified in the graphics commands ListPlot, ParametricPlot, Plot, and Show.

Suppose we want to plot a quarter circle and a 45 degree ray. We could execute the following commands:


        Clear[f, g, x]

        f[x_]:=Sqrt[1-x^2]
        g[x_]:=x

        Plot[ { f[x], g[x]}, {x,0,1}]
      

Unfortunately, the curve doesn't look like part of a circle, nor is the ray at 45 degrees, because Mathematica has chosen different x and y scales. If we don't specify how we want a plot to be displayed, Mathematica makes choices that show the data compactly, but perhaps not in a way that really satisfies us.

In this case, we can force the scales to correspond to the relative lengths signified by the actual coordinates. We do this by specifying the AspectRatio->Automatic option:


        f[x_] := Sqrt[1-x^2]
        g[x_] := x
 
        Plot[ { f[x], g[x]}, {x,0,1} , AspectRatio->Automatic]
      

You may also specify a numeric value for the AspectRatio. For instance, setting AspectRatio->2 makes a new plot that is twice as high as the actual data would justify.

Back to TABLE OF CONTENTS.

Axes

The Axes option determines whether axis lines are displayed on a graph. By default, the axis lines will be drawn, so the main reason to specify this option is to request that axis lines not be drawn. For instance, this command will give you just the sine curve, without the usual x and y axis lines:


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

Back to TABLE OF CONTENTS.

AxesLabel

AxesLabel is an option that may be specified in the graphics commands ListPlot, ParametricPlot, Plot, and Show.

AxesLabel allows you to label the x and y axes of your plot.


        Clear[t]

        Plot [ 1-Exp[-t], {t,0,1}, AxesLabel->{"Time", "Radiation"} ]
      

Back to TABLE OF CONTENTS.

AxesOrigin

AxesOrigin is an option that may be specified in the graphics commands ListPlot, ParametricPlot, Plot, and Show.

Sometimes, Mathematica will not include the origin in your plot:


        Clear[x]

        Plot [ Sin[x]+4, {x,1,10} ]
      

If you want the point (0,0) included, with both axes going through it (or at least pointing towards it) then you might use the AxesOrigin option:


        Plot [ Sin[x]+4, {x,1,10}, AxesOrigin->{0,0}, 
          PlotLabel->"Same plot, with AxesOrigin command" ]
      

A sneaky way to force the x axis to show up is simply to include the line y=0 in your graph. The funny thing is, this graph is a lot nicer than the previous one!


        Plot [ { Sin[x]+4, 0}, {x,1,10} ]
      

Back to TABLE OF CONTENTS.

BarChart

The BarChart command makes a bar chart of a list of data.

The simplest form of the command is


        BarChart[data]
      
where data is a list of values that will be the heights of the bars in the chart.

Here is an example of a command:


        Needs[ "Graphics`Graphics`" ]
        Clear [ salary ]
        salary = { 10000, 12500, 9750, 8000, 13000 }
        BarChart [ salary ]
      

Some useful options include:

The command StackedBarChart[list1, list2, ...] makes a "stacked" bar chart. First the data in list1 is used to make a bar chart, then the data in list2 is added on top of list1 and so on.

Back to TABLE OF CONTENTS.

ContourPlot

A contour plot is used to plot the variation of a scalar quantity over a two-dimensional area. A contour plot may use contour lines, which join points having an equal value of the quanity, or contour areas, which give a single color to all the points having values of the quanitity within a certain range.

To define a contour plot, you're going to need a function f(x,y) and a range for your x and y data. The simplest form of the contour plot command is:


        ContourPlot [ f[x,y], { x, xmin, xmax }, { y, ymin, ymax } ]
      

Thus, for instance, to plot level curves of an ellipse 9*x^2 + 16*y^2 = 144:


        Clear [ f, x, y ]
        f[x_,y_] := 9*x^2 + 16*y^2 - 144
        ContourPlot [ f[x,y], { x, -5, 5 }, { y, -5, 5 } ]
      
or, simply,

        ContourPlot [ 9*x^2 + 16*y^2 - 144, { x, -5, 5 }, { y, -5, 5 } ]
      

Some useful options include:

Back to TABLE OF CONTENTS.

ConvexHull

You can compute the convex hull of a set of points by using the ConvexHull command in the ComputationalGeometry package. What this command does is return a list of the points which define the convex hull. In order to plot the convex hull, you need to add a copy of the first point to the end of the list.


        Needs[ "DiscreteMath`ComputationalGeometry`" ]

        points = {  {-2.5,0.0},  {-1.5,-2.0}, {0.5,-1.5}, {1.0,0.0}, 
                    {-0.5,1.5},  {-2.0,2.0},  {-2.0,1.5}, {0.0,-1.0}, 
                    {-1.0,-1.0}, {-0.5,0.5},  {0.0,-0.5} } 

        myplot1 = ListPlot [ points, PlotJoined->False ]

        mylist = ConvexHull [ points ]
        mylist = Append [ mylist, mylist[[1]] ]

        myplot2 = ListPlot [ points[[mylist]], PlotJoined->True ]

        Show [ myplot1, myplot2 ]
      

Back to TABLE OF CONTENTS.

DelaunayTriangulation

Any set of points in the plane can be used to define a grid of triangles, called a triangulation. There are actually many ways to do this; the Delaunay triangulation joins the points in a way that tries to avoid making "pointy" triangles with a small angle. You might want to first display the points using the ListPlot command.


        Needs[ "DiscreteMath`ComputationalGeometry`" ]
        gxy = {  {0.0,0.0},  {0.0,1.0},  {0.2,0.5}, {0.3,0.6}, 
                  {0.4,0.5},  {0.6,0.3},  {0.6,0.5}, {1.0,0.0}, 
                  {1.0,1.0} } 
        ListPlot [ points, PlotJoined->False ]
        triangles = DelaunayTriangulation [ gxy ]
      

The data structure triangles contains a list of triangle indices, and the three input points that form the corresponding triangle.

To see a plot of the Delaunay triangulation, you can simply process the points directly with the command:


        PlanarGraphPlot [ gxy ]
      

Back to TABLE OF CONTENTS.

Display

The Display command allows you to save a picture as a file, so that you can use the picture in other programs.

The most common form of the command is


        Display [ "file.eps", plot, "EPS" ]
      
where file.eps is the name of the file to be created, plot is the name of the plot to be stored in the file, and EPS specifies that you want the file to be an Encapsulated PostScript file.

Note that, if you don't say otherwise, Mathematica will want to put the output file in a subdirectory of the Mathematica folder. This makes the file hard to find, and if this directory happens to be on a locked disk, then the command will fail, without any warning or message. (How thoughtful). For both reasons, it might be wise to specify a full directory path, so the file goes exactly where you want to. On the Macintosh, you must specify an "absolute path name", which starts with the name of the disk, and proceeds through any subdirectory names, down to the file name, with the items separated by colons. On our system, for instance I might type:


        Display [ "User:myplots:file.eps", plot, "EPS" ]
      

The options for the format of the output file include:

The graphics file created can sometimes be slightly imperfect. In my case, I asked for EPS format, which should be a text file. Somehow, Mathematica convinced the Macintosh that this was actually a binary file. Thus, when I went to transfer the file to another computer, the line control (carriage returns and line feeds) was all wrong, and the file looked like one long line, which made the file not usable. I had to fix the line control problem before the file would work.

On the Macintosh, there is an option that allows you to highlight a graphic cell, and save it as an EPS file. However, the resulting EPS file is poorly constructed, and will not work with many other PostScript programs. For one thing, it lacks a "showpage" command, but there are more problems than that.

Back to TABLE OF CONTENTS.

DisplayFunction

Sometimes, you don't immediately want to see the output of a graphics command such as ListPlot ParametricPlot, or Plot. Instead, you plan to set up several plots, and then show them together with the command Show

You can easily hide the preliminary plots, and only show the composite one, by using the DisplayFunction option:


        Clear[plot1, plot2, x]

        plot1 = Plot[ Sin[x], {x,0,Pi/2}, DisplayFunction->Identity ] 
        plot2 = Plot[ 1, {x, Pi/2, 3.0}, DisplayFunction->Identity] 

        Show[ plot1, plot2, DisplayFunction->$DisplayFunction ]
      

Back to TABLE OF CONTENTS.

GraphicsArray

The GraphicsArray command can be used to modify the behavior of the Show command. Instead of displaying several plots together on one set of axes, you can display two plots side by side, or one above the other. You can also display 6 plots in a 3 by 2 array, and use other arrangements.

Let's suppose that you have already made six plots, with names plot1 through plot6. To simply show two plots next to each other, put them in a list:


        Show[ GraphicsArray[ { plot1, plot2 } ] ]
      
If you want to have more than one row of plots, then you need to make a table, or list of lists. For instance, to arrange six plots in two rows of three, you might use the command:

        Show[ GraphicsArray[ { { plot1, plot2, plot3 }, 
                               { plot4, plot5, plot6 } } ] ]
      
in which case the plots will appear something like this:

        plot1 plot2 plot3
        plot4 plot5 plot6
      

Back to TABLE OF CONTENTS.

GridLines

The GridLines option to the commands ListPlot, ParametricPlot and Plot allows you to request that grid lines be included in your plot. The option GridLines->Automatic has Mathematica choose the placement of the lines:


        Plot[ Sin[x^3], {x,-2,2}, GridLines->Automatic]
      

You may also choose the location of grid lines yourself, by specifying a list of x coordinates and a list of y coordinates. You may want to add the option AspectRatio so that the units of measurement are the same in both directions, as in this example:


        Plot[ ArcTan[x], {x,-2,3},
          GridLines->{ {-2, -1.5, -1, -0.5, 0, 0.5, 1, 1.5, 2},
                       {-1, -0.5, 0, 0.5, 1} },
          AspectRatio->Automatic]
      

To see how to define grid lines for a polar plot, see the discussion of Polar Grids.

Back to TABLE OF CONTENTS.

ImplicitPlot

The ImplicitPlot command allows you to create a plot of an implicit relationship f(x,y)=0 that is not easily resolved into functional form for which the Plot command would be suitable, or parametric form, for which the ParametricPlot would work.

There are two forms of the command, which actually operate in significantly different ways. The two forms differ in the "type" of the graphics output, and hence also in the kinds of graphics options you can specify.

The first form specifies a relationship, and a range for one of the variables only:


        Needs["Graphics`ImplicitPlot`"]
        Clear [ f, x, y ]
        f[x_,y_] := 9*x^2 + 16*y^2 - 144
        ImplicitPlot [ f[x,y] == 0, { x, -5, 5 } ]
      
The procedure Solve is then used to determine suitable values of y corresponding to selected values of x. The type of the graphics output is the same as for a Plot command, and you may use the options suitable for that kind of plot.

The second form specifies a relationship, and a range for both variables:


        Needs["Graphics`ImplicitPlot`"]
        Clear [ f, x, y ]
        f[x_,y_] := 9*x^2 + 16*y^2 - 144
        ImplicitPlot [ f[x,y] == 0, { x, -5, 5 }, { y, -5, 5 } ]
      
In this approach, the results are computed using contour plot techniques. The type of the graphics output the same as for a ContourPlot command, and you may use the options suitable for that kind of plot.

Back to TABLE OF CONTENTS.

LabeledListPlot

The LabeledListPlot command can display a set of points in the plane. similar to the ListPlot command. However, it also automatically displays a numerical label for each point. This can be very handy when constructing a mathematical graph.

A simple example of the command would be:


        Needs["Graphics`Graphics`"]
        Clear[ pairs, x, y ]

        y = { 1.0, 0.0, 1.0, 2.0, 1.0 }
        x = { 0.0, 1.0, 1.0, 1.0, 2.0 }
        pairs = Table[ { x[[i]], y[[i]] }, {i, 1, 4} ]

        LabeledListPlot[ pairs ] 
      

Back to TABLE OF CONTENTS.

ListPlot

The ListPlot command allows you to make a plot out of pairs of data values. In the simplest case, you simply have a single list of data which we'll call y:


        Clear[ y ]

        y = { 1.1, 2.4, 2.2, 2.7, 5, 1.0, 4 }

        ListPlot[ y, PlotJoined->True] 
      

Suppose, however, that you want to plot pairs of values, that is, you have both the x and y coordinates for the points. Then you first need to to join the two lists into a single table, using the Table command:


        Clear[ i, pairs, xvals, yvals ]
        xvals = {0, 1, 3, 2}
        yvals = {4, 1, 5, 4}

        pairs = Table[ { xvals[[i]], yvals[[i]] }, {i, 1, 4} ]

        ListPlot[ pairs, PlotJoined->True ] 
      

In our examples so far, the y value can be regarded as a function of the x value. There is no need for this to be true. You can use the same ListPlot command to display a set of points scattered in the plane. (You probably don't want to join them by lines, though.)


        Clear[ points ]
        points = {  {-2.5,0.0},  {-1.5,-2.0}, {0.5,-1.5}, {1.0,0.0}, 
                    {-0.5,1.5},  {-2.0,2.0},  {-2.0,1.5}, {0.0,-1.0}, 
                    {-1.0,-1.0}, {-0.5,0.5},  {0.0,-0.5} } 
        ListPlot [ points, PlotJoined->False ]
      

You can assign the output of the ListPlot command a name, and then use the command Show to redisplay it.

There are many graphics options available, including Aspect Ratio, AxesLabel, AxesOrigin, GridLines, PlotLabel, PlotRange, and RGBColor.

Back to TABLE OF CONTENTS.

Needs

Many useful commands are not in the main part of Mathematica. For instance, there is a command called ConvexHull, which you might want to use some time. But because it's not in the main part of Mathematica, if you simply type the command ConvexHull, two bad things will happen:

This bizarre feature is a headache you have to learn to live with when using Mathematica. If you've typed in a command and Mathematica doesn't seem to recognize what you mean, you may need to exit Mathematica and start over, to clear its mind!

Anyway, whenever you are using a command that is not part of the main portion of Mathematica, you need to make sure that you give enough information so that that particular command can be found and properly loaded. Mathematica keeps its extra commands in packages, and so before you use a command, you just specify what package you will be needing, using the Needs command. Be careful to type in the double quotes and the backward quotes exactly as they appear here!


        Needs["Graphics`Graphics`"]
      

The command << can be used instead of Needs. However, every time it is invoked, the command reads in a new copy of the requested package, and does not wipe out the old copies. Reading the same package can cause memory or logic problems for Mathematica.


        << Graphics`Graphics`
      

Back to TABLE OF CONTENTS.

ParametricPlot

Most plots are of functions that can be expressed in the form y=f(x). But there are some objects we'd like to draw that don't fit this pattern. In such a case, it is often possible to express both the x and y coordinates of the graph in terms of a helping variable, called a parameter. A plot of such a graph is done by specifying the range of the parameter, not the ranges of x and y.

The points on a circle are exactly the points which satisfy the relationship x^2 + y^2 = r^2, but this equation can't be reduced to the form y=f(x) without leaving out some points. The expression


        y = sqrt ( r^2 - x^2 ) 
      
only produces the top half of the circle, for instance. But the x and y coordinates of a circle of radius r can be expressed in terms of a parameter t as:

        Clear[r, t, x, y]

        r = 2;
        x[t_] := r * Cos[t]
        y[t_] := r * Sin[t]
      
If we let t vary from 0 to 2*pi, the entire circle will be drawn.

For such a situation, Mathematica supplies the ParametricPlot command, which is similar to the command Plot, except that it requires formulas for both x and y as functions of the parameter (which is often called t). Using the definitions we just made above, we can now draw the circle with the command:


        ParametricPlot[ {x[t], y[t]}, {t, 0, 2*Pi}, AspectRatio->Automatic]
      

There are many graphics options available, including Aspect Ratio, AxesLabel, AxesOrigin, GridLines, PlotLabel, PlotRange, and RGBColor.

The command PolarPlot is defined in terms of the ParametricPlot command.

Back to TABLE OF CONTENTS.

PieChart

The PieChart command can be used to make pie charts. There are options to label or color the wedges, to "explode" some or all of them (that is, to move them away from the center). The input to the command is simply a list of data.


        Needs[ "Graphics`Graphics`" ]
        Clear [ x ]
        x = { 1, 4, 4, 8, 3 }
        PieChart [ x ]
      

Options include

Back to TABLE OF CONTENTS.

Plot

The most common Plot command plots one function on a given x domain, letting Mathematica decide how to choose the y range of the plot:


        Clear[f,g,x]

        Plot[ Sin[x], {x,-Pi,Pi} ]
      

To plot two graphs at the same time, you can simply include both formulas in curly brackets (a Mathematica list). To make things clearer, we will give the formulas names first:


        f[x_] := Sqrt[1-x^2]
        g[x_] := x 

        Plot[ { f[x], g[x] }, {x,0,1} ]
      

You can also use the command Show to accomplish this task.

Plots can take up a lot of memory. If you can't save your notebook to a floppy disk because it's too large, try deleting some of your pictures. As long as you leave the actual Plot commands in your file, you can easily get your pictures back the next time you run Mathematica.

You may be interested in the example Plot and D Don't Mix.

There are many graphics options available, including Aspect Ratio, AxesLabel, AxesOrigin, GridLines, PlotLabel, PlotRange, and RGBColor.

Back to TABLE OF CONTENTS.

Plot and D Don't Mix

If you have defined a function f[x_], and you want to plot its first derivative, then the proper way to do this is to use the "prime" or "single quote" symbol in the command Plot:


        Clear[f, x]

        f[x_] := Sin[x]

        Plot[ f'[x], {x,0,Pi} ]
      

You cannot use D[f[x],x] in the Plot command, even though it means the same thing (to us) as f'[x]! This is because the Plot command would see the variable x used twice, once as a symbolic argument, and once as the range of plotting. So the following command won't work:


        Plot[ D[f[x],x], {x,0,Pi} ]
      

You may want to refer to the commands D (Differentiate), or Plot.

Back to TABLE OF CONTENTS.

PlotLabel

PlotLabel is an option that may be specified in the graphics commands ListPlot, ParametricPlot, Plot, and Show.

The PlotLabel option prints a title on your plot. The title should be enclosed in double quotes:


        Clear[x]

        Plot[ Sin[x]*Sin[2*x], {x,0,10},
          PlotLabel->"Product of two Sine functions" ]
      

If you have several plots, each with a plot label, and you show them together with the Show command, only one label will show up. If the Show command specifies a PlotLabel option, then that is the plot label that will appear.

Back to TABLE OF CONTENTS.

PlotRange

PlotRange is an option that may be specified in the graphics commands ListPlot, ParametricPlot, Plot, and Show.

You may often find that you want to change the range that Mathematica chooses for the graph. This is easy to do with the PlotRange option. It can be useful when Mathematica decides to "crop" your graph, omitting very high or very low values. In that case, you can use the option


        PlotRange->All 
      
to force the display of all data.

In other cases, you may want to do some "cropping" yourself. You might want to focus on where a graph crosses the x axis, for instance:


        Clear[f, x]

        f[x_] := (x+1) * (x-2)^2 * x 

        Plot[ f[x], {x,-3,3}, PlotRange->{-1,1} ]
      

Back to TABLE OF CONTENTS.

PlotStyle

PlotStyle is an option to the Plot and ListPlot commands that allows the user to specify the style of the lines and points being drawn. The style includes such items as color, thickness and dashing.

If a single value is given, that value is used for all items. If a list of styles is given, then each style is used in turn as each new line is generated.

The most common item to specify is the color:

Other options include:

Back to TABLE OF CONTENTS.

PlotVectorField

The PlotVectorField command is used to draw a field of vectors. These might represent values of the wind velocity, or the gradient vectors of a surface z(x,y);

To plot a field of vectors (u(x,y), v(x,y)), we simply define the functions associated with the first and second components of the vector, and then give the ranges of the independent variables:


        Needs[ "Graphics`PlotField`" ]
        PlotVectorField [ { u[x,y], v[x,y] }, { x, xmin, xmax }, { y, ymin, ymax } ]
      

Thus, we might want to plot a field of vectors that represent the gradient of x^2+y2:


        Needs[ "Graphics`PlotField`" ]
        Clear[ x, y, u, v ]
        u[x_,y_] := 2 * x
        v[x_,y_] := 2 * y
        PlotVectorField [ { u[x,y], v[x,y] }, { x, -5, 5 }, { y, -5, 5 } ]
      

The command is most often used to display the value of the derivative function associated with an ordinary differential equation. For example, if we are solving the differential equation


        dy/dt = sin(t) + y
      
then the vectors we want to plot are ( 1, sin(t)+y ). We could make a display of what the right hand side looks like at various points with the command:

        Needs[ "Graphics`PlotField`" ]
        Clear [ y, t ]
        PlotVectorField [ { 1, Sin[t]+y }, { t, 0, 2*Pi }, { y, -2, 2 } ]
      

The simplest check of the command is to try to draw the field of vectors tangent to a set of circles. The picture should look like the surface of water swirling around a drain:


        Needs[ "Graphics`PlotField`" ]
        PlotVectorField [ { -y, x }, { x, -2, 2 }, { y, -2, 2 } ]
      

Back to TABLE OF CONTENTS.

Polar Grids

When drawing a function using polar coordinates, it may be convenient to show a set of polar grid lines, that is, a set of regularly spaced circles and rays.

The following Mathematica function circles can be used to draw ncirc circles around the origin, with radius rmin to rmax:


        Clear[circles]

        circles[rmin_,rmax_,ncirc_]:=
          Block[{circplot},
            circplot=Graphics[
              Table[
                Circle[{0,0},(rmin*(ncirc-n)+rmax*(n-1))/(ncirc-1)],
                  {n,1,ncirc}
              ]
            ]
          ]
      

To use the function, choose values for the arguments and call circles. There won't be any output, except for a note from Mathematica saying "Graphics". You should save the output of the command as a variable.


        rmin = 1;
        rmax = 2;
        ncirc = 11;
        p1 = circles[rmin,rmax,ncirc]
      

The grid can be displayed at any time using the command Show.


        Show[p1, AspectRatio->Automatic]
      

The function rays can be used to draw nrays rays from the origin, extending from radius rmin to rmax:


        Clear[rays]

        rays[rmin_,rmax_,nrays_]:=
          Block[ {rayplot},
            rayplot = Graphics[
              Table[
                Line[{{rmin*Cos[n],rmin*Sin[n]},
                      {rmax*Cos[n],rmax*Sin[n]}}],
                  {n,0,2Pi-2*Pi/nrays, 2*Pi/nrays}
              ]
            ]  
          ]
      

As before, the output of rays should be saved in a variable:


        rmin = 0.5;
        rmax = 2;
        nrays = 10;
        p2 = rays [ rmin, rmax, nrays ]
      

Now prepare a graph of your function in polar coordinates, using the command ParametricPlot:


        f[t_] := 2*Cos[3*t]

        p3 = ParametricPlot[ {f[t]*Cos[t], f[t]*Sin[t]}, {t,0,2*Pi},
          AspectRatio->Automatic, PlotStyle->RGBColor[0,0,1] ]
      

To show your function along with the circles and rays that form the grid, use the command Show. Don't forget the option AspectRatio so that your plot doesn't come out squashed:


        Show [ p1, p2, p3, AspectRatio->Automatic ]
      

You may also want to refer to the discussion of the option GridLines, used for (x,y) graphics.

Back to TABLE OF CONTENTS.

PolarPlot

The PolarPlot command produces a plot using a formula of the form


        R = f(Theta).
      

Here, we are using polar coordinates, (R,Theta) to represent points in the plane. The value R represents the radius or distance of a point from the origin, and Theta represents the angle between the x-axis and the line from the origin to the point.

PolarPlot is not a built-in Mathematica command, so you have to request that it be read in. One method of doing this uses the Needs command. Beware! You must type in the double quotes and the backward quotes exactly as they appear here!


        Needs["Graphics`Graphics`"]
      

You could also simply define the PolarPlot command yourself:


        PolarPlot[ r_, {theta_, thetaMin_, thetaMax_}] :=
          ParametricPlot[ {r*Cos[theta], r*Sin[theta]}, {theta,thetaMin,thetaMax},
            AspectRatio->Automatic]
      

PolarPlot expects a formula for the radius R in terms of the angle Theta.


        rFun[theta_] := 2*theta
        PolarPlot[ rFun[theta], {theta,0,20*Pi} ]
      

If Mathematica did not draw a plot in response to the above command, then you have not loaded PolarPlot successfully.

Because of the way PolarPlot is defined in terms of ParametricPlot, you can't add any graphics options, such as RGBColor:


        PolarPlot[ Cos[3*theta], {theta,0,Pi}, PlotStyle->RGBColor[1,0,0]}]
      

So if you really want a flexible way of doing polar plots, you will probably want to use the fourth option, which is not to use the clumsy, inflexible PolarPlot command at all, but instead, use the built-in command ParametricPlot. In that case, we begin by defining the functional dependence of R on Theta:


        rFun[theta_] := Cos[3*theta]

        ParametricPlot[ {rFun[theta]*Cos[theta], rFun[theta]*Sin[theta]},
          {theta,0,Pi}, AspectRatio->Automatic,
            PlotStyle->{RGBColor[1,0,0]}, Axes->None]
      

What if you want to do a polar plot, but you have the unusual situation where Theta is a function of R?

Really, this is just as easy. Simply define the functional dependence of Theta on R, and use an appropriate range for R in your call to ParametricPlot. The following commands make an interesting plot that looks a little like Batman's call sign:


        thetaFun[r_] := Sin[r]

        ParametricPlot[ {r*Cos[thetaFun[r]], r*Sin[thetaFun[r]]},
          {r,-10,10}, AspectRatio->Automatic,
            PlotStyle->{RGBColor[1,0,0]}, Axes->None]
      

Back to TABLE OF CONTENTS.

RGBColor

RGBColor is an option that may be specified in the graphics commands ListPlot, ParametricPlot, Plot, and Show.

If you are drawing two curves on the same plot, you may want to draw them in different colors, using the RGBColor option. The three numbers you specify for each line are the relative amounts of red, green and blue to be used, between 0 and 1.


        Clear[f, g, x]

        f[x_] := Sqrt[1-x^2]
        g[x_] := x

        Plot[ {f[x],g[x]}, {x,0,1}, 
          PlotStyle->{ RGBColor[1.000, 0.000, 0.000],
          RGBColor[0.000, 1.000, 0.000] } ]
      

Back to TABLE OF CONTENTS.

Sampling Plot Coordinates

In some cases, you might want Mathematica to report to you the coordinates of specific locations in a plot that it has displayed.

This is easy to do if you follow these steps:

Now you can copy the coordinates of one or more of the points on the graph into a data array. To do so:

You will get pairs of coordinates in a Mathematica array format. You can assign this data to a matrix or table, and then manipulate it any way you like.

Back to TABLE OF CONTENTS.

Show

For various reasons, you may want to prepare two plots separately, and then show them together on the same grid. One reason would be if you are defining a function using two formulas, each one good over a specific interval. You can graph each piece with the command Plot, being sure to "name" each plot, and then use the Show command to put them together.


        Clear[plot1, plot2, x]

        plot1 = Plot[ Sin[x], {x,0,Pi/2}, PlotLabel->"The Sine piece" ]
        plot2 = Plot[ 1, {x, Pi/2, 3.0}, PlotLabel->"The One piece"] 

        Show[ plot1, plot2 ]
      

If either plot is labeled, then the composite plot will also be labeled. The Show command uses the first label it encounters. If this is a problem, just use the option PlotLabel to make a more appropriate label:


        Show[ plot1, plot2, plot3, PlotLabel->"The composite plot"]
      
Similar commands can show as many plots as you like, all on the same axes.

If you want to put a few plots side by side, or in an array, rather than on the same axes, then look into the GraphicsArray command.

There are many graphics options available, including AspectRatio, Axes, AxesLabel, AxesOrigin, GridLines, PlotLabel, PlotRange, and RGBColor.

Back to TABLE OF CONTENTS.

Text

The Text command is a way to put a letter, word or sentence at any point on a graph or plot.

The use of the Text command is a little awkward, even considering that we're using Mathematica. The easiest way I know is to work with the Show command; you set up your plot first and save the output; then you issue a Show command, and include the text labels. How the command Graphics gets into this business is not suitable for discussion at the moment.

Here, for example, is a sine curve, with a few points labeled:


        picture = Plot [ Sin[x], { x, 0, 2*Pi} ]

        Show [
          picture,
          Graphics[ Text[ "Start",   {0,0} ] ],
          Graphics[ Text[ "Hi point",{Pi/2,1} ] ],
          Graphics[ Text[ "Low",     {3*Pi/2,-1} ] ]
          ]
      

Back to TABLE OF CONTENTS.

VoronoiDiagram

Any set of points in the plane can be used to define "neighborhoods". If we associate with a data point all the points that are closer to that data point than to the others, we divide the plane up into polygonal regions called Voronoi regions. You might want to first display the points using the ListPlot command.


        Clear[ gxy ]
        Needs[ "DiscreteMath`ComputationalGeometry`" ]
        gxy = {  {0.0,0.0},  {0.0,1.0},  {0.2,0.5}, {0.3,0.6}, 
                  {0.4,0.5},  {0.6,0.3},  {0.6,0.5}, {1.0,0.0}, 
                  {1.0,1.0} } 
        ListPlot [ gxy, PlotJoined->False ]
        [ vxy, gface ] = VoronoiDiagram [ points ]
      

The command actually returns two datastructures, vxy, the coordinates of the Voronoi vertices (or in a few cases, descriptions of rays to infinity), and gface, which lists the Voronoi vertices that form the border of each region. If all you want is to see a picture of the Voronoi diagram, then you should now type:


        DiagramPlot [ gxy, vxy, gface ]
      

Back to TABLE OF CONTENTS.

You can return to the HTML web page.


Last revised on 10 January 2008.