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

Shading and coloring your graph


You can shade and color your graphs using the polygon() command. To use the polygon() command, you must specify the horizontal and vertical axis limits, but you must also include the x and y variables as the middle arguments.

Let's create a quadratic curve and shade under it with a light green selected from the Hexadecimal Color Chart:

x <- 1:100
y <- 3*x^2 + 2*x + 7
plot(x, y)
lines(x, y)

polygon(cbind(c(min(x), x, max(x)), c(min(y), y, min(y))), col="#00CC66") 

Here is the graph:

Using this approach, the polygon() command shades under the curve, between the minimum and maximum values of the x variable and below the y variable. The syntax involving cbind() is an elegant way of including the relevant limits.

The following example is more complex. It uses the rnorm() command to simulate values from a normal distribution, with a given mean and standard deviation. By default, random values with a mean of 0 and a standard deviation of 1 are produced. For...