2. Plotting in R#

This chapter is a quick guide to plotting univariate functions in R. Following the discussion you should be able to plot any simple univariate function and customise your graph to look as intended.

All the examples below only use the core functionality of R (available with any installation through the in-built R graphics package) and do not require the installation of additional packages.

Tip

You may find it useful to refer to the official documentation of the R graphics package here. In addition, you can always access R’s documentation regarding any particular function by typing ? followed by the name of the function in the R command prompt. For example, ?plot will return the documentation for the plot() function.

The best way to work through the chapter is to read the discussion and then reproduce all code in your own R/RStudio installation. You can do this by copying code from a notebook cell to your R script and run the code line by line.

The chapter includes some exercises that allow you to test your understanding. It is recommended that you try these exercises on your own before choosing the option to reveal the solutions.

2.1. The basics of plotting in R#

2.1.1. The plot() function#

The most generic (but powerful) function for plotting in R is the function plot() which is invoked by typing

plot(x,y,...)

where

  • x is an \(x\)-coordinate (or a vector of \(x\)-coordinates)

  • y is the corresponding \(y\)-coordinate (or corresponding vector of \(y\)-coordinates)

  • ... are additional optional arguments, discussed below.

2.1.2. Plotting a point#

We start with something very simple - plotting a point.

To plot a point simply type

plot(x,y)

where x is the x-coordinate and y the y-coordinate of the point.

For example to plot the point \(x=1,y=3\) simply type

plot(1,3)
_images/b07dba4eda4733c819d6d558ebb3ff3e92f2d533321014428f0d9462947f828e.png

2.1.2.1. Using optional arguments to customize the point plot#

Notice that when plot() is called without optional arguments

  • a plotting region appropriate for the plot is defined automatically.

    • In the above example the plotting region is automatically set to be \(x\in[0.6,1.4]\) and \(y\in[2,4]\).

    • The plotting region, however, can be set manually with the optional arguments xlim and ylim.

    • For example, xlim=c(0,3) will set the plotting region over the \(x\) axis to \(x\in[0,3]\)

  • axes labels are assigned automatically based on the “names” with which the x and y argument were given.

    • In the above example these were 1 and 2 correspondingly, and this is also how the axes are labeled. Clearly, these are not good axes labels.

    • The axes labels can be set manually with the optional arguments xlab and ylab which take strings as values.

    • For example, xlab="x" will set the \(x\)-axis label to the string x

  • the graph is enclosed in a box

    • the box can be removed by passing frame=FALSE

  • the graph (naturally) appears without a title

    • a title can be set by using main="some text for the title"

  • the point is plotted in black.

    • the color of the plotted object can be set with the argument col and can be assigned either

      • by using the “name” of the color as a string (e.g. col="blue") or;

      • the “number” of the color (e.g. col=2 which turns out to correspond to red)

  • other optional arguments can be used to set the size of the point (cex), shape of point (pch), etc.

For example,

plot(1,3, 
     frame=FALSE, 
     main="Plot of a point", 
     xlim=c(0,6), ylim=c(-2,10), 
     xlab = "x", ylab="y",
     col="red",
     cex=2,
     pch = 17
    )
_images/6cfeac58003aabc7583f43b5215e706750b1884a7b672fd3bd1e88f416eff80f.png
plot(1,3, 
     frame=FALSE, 
     main="Plot of a point", 
     xlim=c(0,6), ylim=c(0,10), 
     xlab = "x", ylab="y",
     col="blue",
     cex=1,
     pch = 19
    )
_images/f24b5c57d73daca0d62a7c76a97fa9b720c76f6d491c99b0a12c13c913e99dd1.png

Tip

You do not need to know all these optional arguments by heart. The important point is to understand how the plot() function works. When you need to produce a specific customized plot you can always check the rich documentation of R, as well as the many online resources, to help you customize your plot.

Exercise 2.1

Reproduce the plot below in your RStudio by setting appropriately main, xlim, ylim, xlab, ylab, col and pch.

_images/ex1.png

2.1.3. Plotting a set of points#

We continue with a small step forward - plotting a set of points.

To plot a set of points we again use

plot(x,y)

but now we need

  • x to be a vector of x-coordinates; and

  • y to be a vector of the corresponding y-coordinates

  • Note: the vectors x and yshould be of the same length (have the same number of elements)

Also recall (section Vectors in the previous chapter) that a vector of specified numbers \([x_1,x_2,...,x_n]\) can be created in R by the code c(x_1,x_2,...,x_n).

For example, to plot the four points \((x=2,y=3)\), \((x=4,y=7)\), \((x=6,y=6)\), \((x=8,y=10)\) simply type

plot(c(2,4,6,8),c(3,7,6,10))
_images/5fffd98fcca4006871f358d37b9750dac667906b265d690205cf7855cacbf349.png

We can again customize the look of the plot by using optional arguments.

Arguments like col, pch, cex, discussed before, work here as well. However, they can now be used in two different ways:

  • As before, if called with a single (scalar) value, then the property is assigned to all points.

    For example, plot(c(2,4,6,8),c(3,7,6,10), col="red") will produce a plot as the above with all points in red.

  • However, they can now be called with a vector of values, in which case the different properties from this vector are assigned sequentially to the distinct points

    For example, plot(c(2,4,6,8),c(3,7,6,10), col=c("red", "blue", "green", "magenta")) will produce a plot with four points of different colours.

See the examples below.

plot(c(2,4,6,8),c(3,7,6,10), 
     col="red", 
     xlim=c(0,10), ylim=c(0,12), 
     xlab="x", ylab="y", 
     frame=FALSE,
     main = "Plot of points"
    )
_images/1ebb4c51f352f28b6359a68ee0d9c8ba5429b92d7bb2c4875ed8808bc1af8008.png
plot(c(2,4,6,8),c(3,7,6,10), 
     col=c("red", "blue"), 
     pch=19, 
     xlim=c(0,10), 
     ylim=c(0,12), 
     xlab="x", ylab="y", 
     frame=FALSE,
     main = "Plot of points"
    )
_images/545c4ba258d44d8b0bb0b2326aaa0b4ab8bb3fbaea0cb49e53486744b3a3753d.png
plot(c(2,4,6,8),c(3,7,6,10), 
     col=1:4, 
     pch=1:4, 
     xlim=c(0,10), ylim=c(0,12), 
     xlab="x", ylab="y", 
     frame=FALSE,
     main = "Plot of points"
    )
_images/53d64cd71b4c2021e39ef08688427876bce67a88b26bbfd6d0388923833646c2.png

Exercise 2.2

The figure below

  • plots the points \((x=1,y=3)\), \((x=2,y=2)\), \((x=3,y=5)\), \((x=4,y=3)\) and \((x=5,y=7)\).

  • on the plotting region \(x\in[0,6]\) and \(y\in[0,8]\)

  • in red color

  • as solid dots (pch=19)

  • and with a title.

_images/ex2.png

Reproduce this plot in your RStudio.

2.1.4. Plotting a function of one variable#

Once we know how to plot individual points, we are conceptually ready to extend the idea to the context of graphs of functions. This turns out to be very easy in R and conceptually very similar to plotting points.

The idea is as follows:

2.1.4.1. Step 1#

Define a vector, x, of evenly spaced \(x\) coordinates over the domain on which you want to plot (recall the discussion in Vectors for creating vectors of evenly spaced numbers).

For example, to plot \(y=5x+4\) over the domain \(x\in[-5,5]\), first define the \(x\) coordinates as

x <- -5:5

2.1.4.2. Step 2#

Define a vector, y, of the corresponding \(y\) coordinates.

For example, given \(y=5x+4\) and the already defined vector x

y <- 5*x+4

Warning

When using the basic arithmetic operators +, -, *, /, ^ on vectors in the programming sense (i.e. data structures) in R, the operations are applied to each element of the vector pointwise. For example, if we have a vector defined as x <- c(1,2,3), then the outcome of the operation y <- x^2 + 2 is identical to y <- c(3,6,11) as

  • \(1^2+2=3\)

  • \(2^2+2=6\)

  • \(3^2+2=11\)

This allows us to easily define \(y\) coordinates given a vector of \(x\) coordinates.

However, notice that this is not how arithmetic operations for vectors are defined in mathematics. We will learn about how arithmetic operations on vectors work mathematically (and how the mathematically consistent arithmetic operations on vectors are implemented in R) later in the course. For now just keep in mind that this is one instance of the distinct meanings of the word vector in programming and mathematics.

2.1.4.3. Step 3#

Plot x against y, using the optional argument type and setting it to "l" (for line)

plot(x, y, type="l")

plot(x,y, type = "l")
_images/b821c528fe3831349aa6851e79dda0157e6d83feb523638b4117de241fb1af42.png

And this is it.

This procedure works for every univariate function defined through expression that you might want to plot.

Note that if we had not set the type argument, it would have taken its default value (type="p") and we would have plotted a set of points on the graph of the function corresponding to the defined coordinates.

plot(x,y)
_images/9e5355b7e035a826feb974fd58efaf25191756e2328b3cf54ff5f110885f2012.png

Instead, by using type="l" R suppresses the plotting of the point circles at the coordinates, but instead draws line segments connecting the coordinates.

Note that we can also use type="b" for both, which will produce a graph with the points and with the line segments connecting them.

plot(x,y, type="b")
_images/4c50aa3f85e473ac13f568d10a32e11e03a11281ac2607593564e4e27554f09b.png

We can further customize the way the graph looks but we will return to this later.

Now instead let’s consider plotting a more interesting function.

2.1.4.4. Example: A cubic function#

Plot \(y=x^3-4x\) for \(x\in[-3,3]\)

x <- -3:3
y <- x^3 - 4*x
plot(x,y,type="l")
_images/18b8f463c9caf832b8ea8651889d6a2cbb629a85d6a1cdca537b903a8530fe6a.png

Notice the problem: when we set type="l" what R actually does is draw line segments connecting the points on the graph of the function.

Previously this was not a problem because the function we plotted was a straight line. In this case, however, the function is non-linear and the graph of the function appear too jumpy.

The problem can be visualized clearly if we were to plot both the line segments and the points.

plot(x,y,type="b")
_images/52b172414b94be2e6a1f16994c0b9e8f3a09752d7b53208bab56e183512b3bd9.png

The solution is very simple - we need a finer grid for the coordinates (basically, we want the distance between elements of the vector x to be smaller).

This can be achieved by using the seq() funcion instead of the colon operator, :, and setting the distance between elements in x sufficiently small. For example, let’s make the distance between elements only 0.25 instead of 1.

x <- seq(-3, 3, by=0.25)
y <- x^3 - 4*x
plot(x,y, type="l")
_images/2755af2df047ce8f51d4a793b1eda765617c885e0194d415c2c2144583489c37.png

And now we have a smooth (to the eye) graph.

Even though R still plots line segments between the points, the number of points on the graph plotted is sufficiently large that to the eye the graph appears smooth. This can be visualized by plotting both the points and the lines as before.

plot(x,y, type="b")
_images/544db1e167488d46be57948547422ca2b0dca3a608318caed701ffa7ba2eb98e.png

Note

At this stage, this might look like cheating. Surely, if we magnify the image sufficiently what we will see is a set of connected straight line segments rather than a proper curve. While this is true, this is the case with even the most sophisticated program for computer graphics. In maths we are accustomed with the idea that in any interval there are infinitely many real numbers and therefore if we were to plot “properly” we could have a “perfect” curve and as much as we magnify the image we won’t see segments connecting points. However, the notion of “infinitely” many points is not something with which computers can deal with. All computer graphics is based on finite numbers of points and segments.

Enough philosophy. The important point is that in exactly the same way you can plot any univariate function you like.

Exercise 2.3

The graph below plots the function \(y=x^2-4\) for \(x\in[-2,2]\).

_images/ex3.png

Reproduce this graph in your RStudio.

2.2. Customizing the look of a simple graph#

2.2.1. Using optional arguments#

As in Using optional arguments to customize the point plot we can use optional arguments to customize the appearance of the line plot

Optional arguments, as before, include

  • xlim and ylim for setting the plotting region

    • although this is usually unnecessary as the default plotting region is typically especially appropriate for showing the graph of the particular function on the specified domain.

  • xlab and ylab for setting the axes labels.

  • col for setting the colour of the line.

  • frame to enable/disable to box.

When plotting lines/curves as here we can additionally use

  • lwd to set the width of the plotted line. Default is lwd=1.

  • lty to set the type of the plotted line.

    • the default is lty=1 or equivalently lty="solid", producing a solid line

    • lty=2 or lty="dashed" produces a dashed line

    • lty=3 or lty="dotted" produces a dotted line

    • etc

x <- seq(-3, 3, by=0.25)
y <- x^3 - 4*x
plot(x,y, type="l",
    main = "Plot of a function",
    frame = FALSE,
    lwd=2,
    lty="dashed",
    col="magenta")
_images/5f92abb31d7a1acc95510c08fa22c74f6f64114246eb3b8ed748664af4c26ecc.png

If we use type=b plotting both lines and points, we can also set the graphical properties of the points with the familiar cex, pch, etc arguments.

plot(x,y, type="b",
    main = "Plot of a function",
    frame = FALSE,
    lwd=2,
    lty="solid",
    col="magenta",
    pch=3,
    cex=0.5)
_images/be3b783ff1b5a66ac36be5763e17f1b90a927db1c823c536bc4af8cbc539b9bf.png

Exercise 2.4

Given the graph of \(y=x^2-4\) for \(x\in[-2,2]\) you plotted in Exercise 2.3, set graphical parameters appropriately to reproduce the plot below.

_images/ex4.png

2.2.2. Using LaTeX for labels and titles#

In some cases we may want to add mathematical text to our graphs, e.g. in titles, labels, text annotations, etc.

However, by default, all text objects under the default functionality of graphics are set and visualized as strings.

For example, if we add a title “Plot of x^3-4x” to the graph, the title string will be typeset as below.

x <- seq(-3, 3, by=0.25)
y <- x^3 - 4*x

plot(x,y, type="l",
    main = "Plot of x^3 - 4x")
_images/9c7cdf65558867200ceeeae9add84df0551f3fc4d12fc120f46b244fca005b0e.png

By using the additional R package latex2exp we can add mathematical text to our graphs.

To install and load the package, type

install.packages("latex2exp")
library(latex2exp)

Then, to set any text object use the following syntax

TeX(r"(YOUR TEXT IN LATEX)")

where YOUR TEXT IN LATEX is anything typed in LaTeX. Note that the string is enclosed in parentheses and brackets and preceded by the letter r.

plot(x,y, type="l",
    main = TeX(r"(Plot of $x^3 - 4x$)")
    )
_images/6261e5283deb4ff66b50bc60d1a5aa31bc9c2e2aa476d9bebafb8b1d82037062.png

2.2.3. Adding additional plots to the same graph#

Once we have called plot() and opened an initial plotting window we can add additional objects to the graph by additionally calling functions such as

  • points(x,y,...) adds points at the specified (x,y)-coordinates of the initial plot

    • this does the same as plot(x,y,type="p") but plots the point on top of the initial plot constructed by the initial call of plot().

    • all optional arguments related to plotting points from Using optional arguments to customize the point plot can be used in the place of ...

  • lines(x,y,...) adds “lines”

    • this does the same as plot(x,y,type="l") but plots on top of the initial plot constructed by the initial call of plot()

    • all optional arguments from Using optional arguments can be used in the place of ...

  • text(x,y,text,...) adds text annotations at the specified coordinates, with the specific text annotations set in text.

  • grid() adds a grid

  • axis(side,...) adds axes

  • legend() adds legend

  • arrows(x0,y0,x1,x2,...) adds an arrow pointing from (x0,y0) to (x1,y1)

  • etc

Note

Keep in mind that the plotting region is set with the initial call of plot() and does not change when we add additional objects to the plot.

2.2.3.1. Adding a grid#

For example, we can add a grid.

plot(x,y, type="l")
grid()
_images/2bcbf2a977b5d6a9903c44bb2347a5423c5dac845048bbe8f6bd1e45c53d9757.png

2.2.3.2. Plotting several functions on the same graph#

It is straightforward to plot more than one functions on the same graph.

First, given a vector of x coordinates, define one new vector of y coordinates for each additional function, say y1, y2, y3, etc.

Then run plot(x,y1, type="l") to plot the first function. This opens a graph and sets the plotting region which remains constant henceforth.

Now

  • add lines(x,y2) to add the graph of the second function to the plotting region.

  • add lines(x,y3) to add the graph of the third function to the plotting region.

  • and so forth

The code will look like

plot(x,y1,...)
lines(x,y2,...)
lines(x,y3,...)
...

where ... are optional arguments at each round.

For example, to plot both \(y=x^3-4x\) and \(y=8x^2+16x\) on the same graph:

  1. First, create a set of y coordinates for each of the two functions

x <- seq(-3, 3, by=0.25)
y1 <- x^3 - 4*x
y2 <- 8*x^2+16*x
  1. Next type

plot(x,y1, type="l",
     xlab="x", ylab="y",
     frame=FALSE)

lines(x,y2)

grid()
_images/2e1933e8a09805822a99abe064c86bb0d1e3c880cee81cbc6232cc283164b9ff.png

It is a good idea to plot the different functions with different graphical properties to make it easier to distinguish.

Say different colors

plot(x,y1, type="l", col="red", frame=FALSE, xlab="x", ylab="y")
lines(x,y2, col="blue")
grid()
_images/dd611b464088729c025931fd264d8f4bf7e36b8e968faf4852a55a790c970062.png

Or different line types

plot(x,y1, type="l", lty=1, frame=FALSE, xlab="x", ylab="y")
lines(x,y2, lty=2)
grid()
_images/bba3064b6babab5986e4340d4ccc0be01168e3039e6b6c7fc4dd3a894568d4f4.png

Or both

plot(x,y1, type="l", col="red", frame=FALSE, xlab="x", ylab="y")
lines(x,y2, lty=2, col="blue")
grid()
_images/40cc044ab9f6271eab46c9986fff102dedeae23babcf47714d7f3a792fc39bf7.png

Note that the plotting region is defined at the point one calls plot(). Therefore, if we we don’t set xlim and ylim manually R will choose a plotting region which is more natural for the function plotted in the initial call of plot().

For example, if we first plotted the second function, and then the first, the graph would look like

plot(x,y2, type="l", col="red", frame=FALSE)
lines(x,y1, col="blue")
_images/1f48a34dcc74b3196b5895b7d3d2b798f1baf761cbfd7955e0464384fca03f29.png

2.2.3.3. Adding a legend#

When we plot more than one function it makes sense to use a legend to show which curve is which function. This can be achieved by using the function legend().

The usage is as follows

legend(position, legend, properties,...)

where

  • position is

    • either a pair of \(x\) and \(y\) coordinate for where the legend to appear

    • or a keyword such as “topleft”, “topright”, “bottomleft”, “top”, etc

  • legend (argument) is a vector of labels, one for each item that needs to be labeled.

  • properties include a corresponding list of graphical properties of the items labeled. These should be set to be the same as the actual graphical properties used in plotting.

plot(x,y1, type="l", frame=FALSE, 
     xlab="x", ylab="y",
     lty=1, col="red"
     )

lines(x,y2, 
      lty=2, col="blue")

grid()

legend(1,-10, 
       legend=c(TeX(r"($x^3+2x$)"),TeX(r"($8x^2+3x$)")), # assign first label to y1, second to y2
       lty=c(1,2),                                       # assign line-type 1 to y1, and 2 to y2 (as this is how we plotted them)
       col=c("red", "blue"),                             # assing red to y1 and blue to y2 as this is how we plotted them     
       bty="n")                                          # disable the box around the legend (you can omit this to see what happens)
_images/b33b397a0809c292a2bb2f91f0b2a85d28e28396fa6f34ffde7fbaf235fb5692.png

2.2.3.4. Adding additional points to the graph#

We can add points to the graph by using the points() function. It’s usage is the same as the usage of plot() in the context of plotting points (Plotting a set of points) but the only difference is that now the plot region and an initial plot are defined by the original call of plot().

For example, we can add points at the intersections of the two curves above which occur at \((x=-2, y=0)\) and \((x=0, y=0)\)

plot(x,y1, type="l", frame=FALSE, 
     xlab="x", ylab="y",
     lty=1, col="red"
     )


lines(x,y2, 
      lty=2, col="blue")

points(c(-2,0),c(0,0), col="magenta", cex = 0.8, pch=19)

grid()
_images/522269f74045abfc4fdde5387c402507ba51ca1f958c51bd19eff0b7629ee362.png

2.2.3.5. Adding text annotations to a graph#

We can use

text(x,y,"text",...)

to add annotation where

  • x and y are the \(x\) and \(y\) coordinates for the location at which the text annotation is to appear

  • "text" is the text to appear at these coordinates

  • ... are optional arguments

An important optional argument is pos which determines where the text should appear relative to the specified coordinates.

  • pos=1 will make the text appear below the coordinate

  • pos=2 will make the text appear to the left of the coordinate

  • pos=3 will make the text appear above the coordinate

  • pos=4 will make the text appear to the right of the coordinate

For example, we can add text labels to the right of the two points above by using

plot(x,y1, type="l", frame=FALSE, 
     xlab="x", ylab="y",
     lty=1, col="red"
     )


lines(x,y2, 
      lty=2, col="blue")

points(c(-2,0),c(0,0), col="magenta", cex = 0.8, pch=19)

text(c(-2,0),c(0,0), c("A", "B"), pos=4)

grid()
_images/a5cc6392c1ded45d89cfd99f5e4f77cc86af86021e01c1496ccd157242798242.png

Exercise 2.5

The graph below plots \(y=x^3\) and \(y=x^2\)

  • for \(x\in[-2,2]\)

  • in different colours

  • adds a legend with TeX labels

  • plots points at the intersections of the two graphs occurring at \((x=0,y=0)\) and \((x=1,y=1)\)

  • and adds some text below the points.

_images/ex5.png

Reproduce this plot in your RStudio.

2.2.3.6. Adding vertical and horizontal lines to your plots#

In general, lines can be added to a graph using the abline() function.

To add a horizontal line at some value, c, of \(y\), call abline(h=c)

To add a vertical line at some value, d, of \(x\), call abline(h=d)

For example, let’s add dashed vertical lines going through the points A and B above.

x <- seq(-3, 3, by=0.25)
y1 <- x^3 - 4*x
y2 <- 8*x^2+16*x
plot(x,y1, type="l", frame=FALSE, 
     xlab="x", ylab="y",
     lty=1, col="red"
     )


lines(x,y2, 
      lty=2, col="blue")

points(c(-2,0),c(0,0), col="magenta", cex = 0.8, pch=19)

text(c(-2,0),c(0,0), c("A", "B"), pos=4)

abline(h=0, lty="dashed")
abline(v=c(-2,0), lty="dashed")

grid()
_images/bfc3c826ed4a53af245b33d732a2c76e4dbfc662e4457fad775b931382087815.png

This is not necessarily a good use of lines, but the point is to demonstrate what is possible.

2.2.3.7. (Optional) Customizing the axes#

By default axes are plotted at the edges of the plotting region.

In some cases we might want to have them plotted elsewhere. For example, we might want axes to pass through the origin \((x=0,y=0)\).

The way to do this is a bit cumbersome but not too difficult.

To draw custom axes following the use of plot(), use the function axis() with the following syntax

axis(side, ...)

where

  • side is set to 1 for horizontal and 2 for vertical axis

  • ... are graphical parameters

  • one important graphical parameter is pos which determines the “position” of the axis. Set pos=0 to make axis go through zero.

Let’s start by just adding a new horizontal and vertical axes through zero:

x <- seq(-3, 3, by=0.25)
y <- x^3 - 4*x
plot(x,y, type="l") 
grid()
axis(1,pos=0)
axis(2,pos=0)
_images/1c17acb4d7dd843ab335d815e1575ac8fc1a914da86a74ff0553f5b9cea9e5ca.png

However, this is not what we want, as the original axes remain. To disable them, use option axes=FALSE inside the initial plot() command

plot(x,y, type="l", axes=FALSE)
grid()
axis(1,pos=0) 
axis(2,pos=0) 
_images/510ba6620bbe6b91f0bf2cf1e1f2026567b5ece87a6525d1a4774d47d896beb9.png

We may want the tick labels on the vertical axes to be rotated. Use las=2 argument inside axis(2,...)

plot(x,y, type="l", axes=FALSE)
grid()
axis(1,pos=0) 
axis(2,pos=0, las=2) 
_images/cc61d75043f85213eb44cf286f626e0f71cb82557c5d8864911883e9a4aae70b.png

Perhaps we don’t want all these ticks. We can disable the ticks by setting their width to zero, and also turn off the labes.

plot(x,y, type="l", axes=FALSE)
grid()
axis(1,pos=0, lwd.ticks=0, labels=FALSE) 
axis(2,pos=0, las=2, lwd.ticks=0, labels=FALSE) 
_images/f70ddd671c33c2a21e1e0146bd7c7786b17f78a1447c705f9e758adee1e099b9.png

Or we can add manual “ticks” (by plotting points) and labels (by using text annotation)

plot(x,y, type="l", axes=FALSE)
grid()
axis(1,pos=0, lwd.ticks=0, labels=FALSE) 
axis(2,pos=0, las=2, lwd.ticks=0, labels=FALSE) 
points(c(-2,2),c(0,0),pch=3)
text(-2,0,"-2", pos=1, cex=0.8)
text(2,0,"2", pos=1, cex=0.8)
_images/e5a107d2d5521aa5df760231b1328ab3b38163948645b685970cd9c7dc5cdb61.png

In more schematics graphs, axes are often plotted with arrows in the direction of increase.

We can use the function arrows() to plot an arrow. The usage is as follows

arrows(x0, y0, x1, y1)

plots a line with an arrow, from the point \((x=x0, y=y0)\) to the point \((x=x1, y=y1)\).

Setting these equal to the x-y limits of the plotting region we can get

plot(x,y, type="l", axes=FALSE)
grid()
arrows(x0=-3,y0=0,x1=3,y1=0)
arrows(x0=0,y0=-15,x1=0,y1=15)
_images/1ac07317a42b7428bd96996e26ca49928bfe32002fd7946acf212a0a74023a09.png

To reduce the size of the arrows use the argument length which sets the length of the arrow head in inches

plot(x,y, type="l", axes=FALSE)
grid()
arrows(x0=-3,y0=0,x1=3,y1=0, length=0.1)
arrows(x0=0,y0=-15,x1=0,y1=15, length=0.1)
_images/0d91b0452c7e8f9b4bbad2bb3c4fcf8b2c1d4a2f8bcc8d8e1f7cc18766b91304.png

We can also “move” the axes labels to the arrows by using text annotation (while also disabling the original labels in the plot() function by setting them to empty strings)

plot(x,y, type="l", axes=FALSE, xlab="", ylab="")
grid()
arrows(x0=-3,y0=0,x1=3,y1=0, length=0.1)
arrows(x0=0,y0=-15,x1=0,y1=15, length=0.1)
points(c(-2,2),c(0,0), pch=3, cex=0.5)
text(c(-2,2),c(0,0), c("-2","2"), pos=1, cex=0.7)
text(3,0,"x", pos=1, cex=0.8)
text(0,15,"y", pos=4, cex=0.8)
_images/1e2143bf5c549e5fa997988d008db9a607cd45f382b985c34624a5efd0a9131a.png

2.2.4. (Optional) Combining multiple graphs into a single figure#

We can cobine multiple graphs into a single figure.

First, tell R that the next figure should be a “plotting matrix” of plots with number_of_rows rows and number_of_columns columns

par(mfrow=c(number_of_rows,number_of_columns))

After this, the next number_of_rows x number_of_columns times you pass plot(), each resulting plot will be placed into this “plotting matrix”.

For example, to plot a figure with the graph of \(y=x^3-4x\) on the left and \(y=8x^2+16x\) on the right, set

par(mfrow=c(1,2))

to create a “plotting matrix” of one row and two columns.

Next call plot() two times, once for each plot.

It is a good idea to finally reset the “plotting matrix” to only plotting a single graph next time by using par(mfrow=c(1,1))

x <- seq(-3, 3, by=0.25)
y1 <- x^3 - 4*x
y2 <- 8*x^2+16*x
par(mfrow=c(1,2))

plot(x, y1, type="l", frame=FALSE, main = TeX("Graph of $y=x^3-4x$"), ylab="y")
grid()

plot(x, y2, type="l", frame=FALSE, main = TeX("Graph of $y=8x^2+16x$"), ylab="y")
grid()

par(mfrow=c(1,1))
_images/003ef78bb841f6c57c531f0b868c97b9cb921eb395fec53ab1a2d3b97547df7d.png

2.3. (Optional) Additional examples#

Below is a list of some more complicated examples without explanation.

You can reproduce these as an exercise.

x <- seq(from=-2, to=2, by=0.25)

y1 <- 3^x
y2 <- 2^x
y3 <- 1^x
y4 <- (1/2)^(x)
y5 <- (1/3)^(x)

plot(x, y1, type="b", col=2, lty=2, pch=2, frame = FALSE, ylab = "y")
lines(x, y2, type="b", col=3, lty=3, pch=3)
lines(x, y3, type="b", col=4, lty=4, pch=4)
lines(x, y4, type="b", col=5, lty=5, pch=5)
lines(x, y5, type="b", col=6, lty=6, pch=6)
grid()
legend("top", c(TeX("$3^x$"),TeX("$2^x$"),TeX("$1^x$"),TeX("$2^{-x}$"),TeX("$3^{-x}$")), lty=2:6, col=2:6, pch=2:6, bty="n")
title("Graphs of exponential functions")
_images/bbf1a33a64852b33ffd458d3346be7b94eadf0a4715d22ec6f39d4d815fbcc0b.png
x <- -1:10
y1 <- 5-x
y2 <- x-3

plot(x, y1, type = "l", lty=1, xlim=c(-2,11), ylim=c(-6,8), lwd=1, axes=F, xlab="", ylab="")
lines(x,y2, type = "l", lty = 4)
arrows(-1,0,10,0, length=0.1, lwd=2)
arrows(0,-4,0,7, length=0.1, lwd=2)
text(10,0,"x", pos=4)
text(0,7,"y",pos=4)
axis(1,at=c(3,4,5), pos=0)
axis(2,at=c(-3,1,5), pos=0, las=2)
points(4,1, pch=19)
segments(0,1,4,1, lty=2)
segments(4,0,4,1, lty=2)
legend("bottom", title="Legend", legend=c(TeX("$y=5-x$"),TeX("$y=x-3$")),lty=c(1,4), bty="n")
title("Graphical solution to a system of two linear equations")
_images/45b4581ca477aac65637c6fa2e93e4a02ce918f34b841eba127afee923256ea8.png
x=seq(-2,2,by=0.1)
y1 = x^2 - 2
y2 = x^2
y3 = x^2 + 2
y4 = -x^2 + 2
y5 = -x^2
y6 = -x^2 - 2

par(mfrow=c(2,3))

plot(x, y1, type = "l", axes = FALSE, ylim = c(-3, 6), xlab="", ylab="")
arrows(-2,0,2,0, length=0.1)
text(2,0, "x", pos=1)
title(TeX("$a>0$ and $D>0$"))
grid()

plot(x, y2, type = "l", axes = FALSE, ylim = c(-3, 6), xlab="", ylab="")
arrows(-2,0,2,0, length=0.1)
text(2,0, "x", pos=1)
title(TeX("$a>0$ and $D=0$"))
grid()

plot(x, y3, type = "l", axes = FALSE, ylim = c(-3, 6), xlab="", ylab="")
arrows(-2,0,2,0, length=0.1)
text(2,0, "x", pos=1)
title(TeX("$a>0$ and $D<0$"))
grid()

plot(x, y4, type = "l", axes = FALSE, ylim = c(-6, 3), xlab="", ylab="")
arrows(-2,0,2,0, length=0.1)
text(2,0, "x", pos=1)
title(TeX("$a<0$ and $D>0$"))
grid()

plot(x, y5, type = "l", axes = FALSE, ylim = c(-6, 3), xlab="", ylab="")
arrows(-2,0,2,0, length=0.1)
text(2,0, "x", pos=1)
title(TeX("$a<0$ and $D>0$"))
grid()

plot(x, y6, type = "l", axes = FALSE, ylim = c(-6, 3), xlab="", ylab="")
arrows(-2,0,2,0, length=0.1)
text(2,0, "x", pos=1)
title(TeX("$a<0$ and $D>0$"))
grid()

mtext("Graphs of quadratic functions, 1",side=1,line=-2,outer=TRUE)
_images/da4e45a3ecf00435e3da79999084abbec18ed58c43fc40f8a8725839d8664249.png
x=seq(-2,2,by=0.1)
y1 = x^2 - 2
y2 = x^2
y3 = x^2 + 2
y4 = -x^2 + 2
y5 = -x^2
y6 = -x^2 - 2

par(mfrow=c(2,3))

plot(x, y1, type = "l", axes = FALSE, xlab="", ylab="")
arrows(-2,0,2,0, length=0.1)
text(2,0, "x", pos=1)
title(TeX("$a>0$ and $D>0$"))

plot(x, y2, type = "l", axes = FALSE, xlab="", ylab="")
arrows(-2,0,2,0, length=0.1)
text(2,0, "x", pos=1)
title(TeX("$a>0$ and $D=0$"))

plot(x, y3, type = "l", axes = FALSE, xlab="", ylab="")
arrows(-2,0,2,0, length=0.1)
text(2,0, "x", pos=1)
title(TeX("$a>0$ and $D<0$"))

plot(x, y4, type = "l", axes = FALSE, xlab="", ylab="")
arrows(-2,0,2,0, length=0.1)
text(2,0, "x", pos=1)
title(TeX("$a<0$ and $D>0$"))

plot(x, y5, type = "l", axes = FALSE, xlab="", ylab="")
arrows(-2,0,2,0, length=0.1)
text(2,0, "x", pos=1)
title(TeX("$a<0$ and $D>0$"))

plot(x, y6, type = "l", axes = FALSE, xlab="", ylab="")
arrows(-2,0,2,0, length=0.1)
text(2,0, "x", pos=1)
title(TeX("$a<0$ and $D>0$"))

mtext("Graphs of quadratic functions, 2",side=1,line=-2,outer=TRUE)
_images/372ff9a0d9febe04687d5413a398d0e4086b14e55f926786d574fb22f6784742.png

This completes the chapter on Plotting in R. In the next chapter we turn attention to using user-defined functions in R.