Book Image

R Graph Essentials

Book Image

R Graph Essentials

Overview of this book

This book is targeted at R programmers who want to learn the graphing capabilities of R. This book will presume that you have working knowledge of R.
Table of Contents (6 chapters)
5
Index

R provides many options

Often, R provides several ways to achieve what you want. Let's set up 50 values from -pi to +pi and graph a sine function. We use the seq() command to set up this sequence. Note that R understands the constant Pi, whose value can be obtained using the following command:

pi

The following output is obtained:

[1] 3.141593

Now, we create horizontal and vertical axis points for plotting:

x <- seq(-pi, pi, length = 50)    
y <- sin(x)  
                     
plot(x, y, pch = 17, cex = 0.7, col = "darkgreen") 

Then, we add a line that connects the points:

lines(x, y, col = "darkgreen")  

Let's take a look at the resulting graph:

R provides many options

Now try the following approach, using 1000 axis values in order to create a smooth-looking graph:

x <- seq(-pi, pi, length = 1000)
y <- sin(x)

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

The output is as follows:

R provides many options

The argument type = "l" produces connecting lines, but here we have so many points that the graph appears smooth. Other options include the argument type = "o", which produces symbols joined by straight lines, and type = "p", which produces points.