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

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:

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:

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.