Book Image

R Graph Essentials

Book Image

R Graph Essentials

Overview of this book

Table of Contents (11 chapters)
R Graph Essentials
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Creating scatterplots and line plots


We have just created a basic graph, but we need more practice. Let's create another plot using the plot() command. First we set up a vector of horizontal axis values called X, and then a vector of vertical axis values called Y. Enter the following syntax on the command line:

X <- c(1, 2, 3, 4, 5, 6, 7, 8)

Y <- c(2, 6, 7, 10, 17, 19, 23, 29)

Now let's graph Y against X.

plot(X, Y, pch = 16)

You'll get the following graph:

That was simple! However, our graph is very basic. Note that R has decided to create axis ticks every five units on the Y axis. Also, note that if you don't provide horizontal axis values (an x axis), by default R will plot your values against a running index.

Let's start again and enhance the graph. Now, we will plot Y using red points using the following command:

plot(X, Y, type = "o", col = "red", xlab = "MY X LABEL", ylab = "MY Y LABEL") 

The argument type="o" produces symbols joined by straight lines. Now, let's create a title using the title() command and the arguments font.main and col.main to control the title font and colors.

title(main = "PLOT 3", font.main = 2, col.main = "blue")

Let's look at our graph.

As expected, we have created a title in blue and joined each point with a red line segment.

The font number is an integer between 1 and 5, where 1 is plain, 2 is bold, 3 is italic, 4 is bold italic, and 5 is symbol.

Notice how to create a title. The following are the main font options for graphs:

  • font.axis: This option specifies the font for the axis annotations

  • font.lab: This option specifies the font for the axis labels

  • font.main: This option specifies the font for the (main) title

  • font.sub: This option specifies the font for a subtitle