Chapter 6 Default Line Plots in R

Note that the function lines() need a plot().

Basic line plots:

Example-1:

par(mfrow=c(2,1), mar=c(3,3,1,0)+.5, mgp=c(1.6,.6,0))
x <- 1:10
y1 <- x*x
y2  <- 3*y1
# Basic stair steps plot 
plot(x, y1, type = "S",plot="pink")
## Warning in plot.window(...): "plot" is not a graphical parameter
## Warning in plot.xy(xy, type, ...): "plot" is not a graphical parameter
## Warning in axis(side = side, at = at, labels = labels, ...): "plot" is not
## a graphical parameter

## Warning in axis(side = side, at = at, labels = labels, ...): "plot" is not
## a graphical parameter
## Warning in box(...): "plot" is not a graphical parameter
## Warning in title(...): "plot" is not a graphical parameter
# Points and line
plot(x, y1, type = "b", pch = 19, 
     col = "blue", xlab = "x", ylab = "y")

Example-2: As functions for different types

x <- c(1:5); y <- x*x # create example data 
par(pch=22, col="blue") # plotting symbol and color 
par(mfrow=c(2,4)) # all plots on one page 
opts = c("p","l","o","b","c","s","S","h") 
for(i in 1:length(opts)){ 
  heading = paste("type=",opts[i]) 
  plot(x, y, type="n", main=heading) 
  lines(x, y, type=opts[i]) 
}

Example-3: Plot the points type=“”

x <- c(1:5); y <- x*x # create example data
par(pch=22, col="#00AE68") # plotting symbol and color 
par(mfrow=c(2,4)) # all plots on one page 
opts = c("p","l","o","b","c","s","S","h") 

for(i in 1:length(opts)){ 
  heading = paste("type=",opts[i]) 
  plot(x, y, main=heading) 
  lines(x, y, type=opts[i]) }

Multiple lines plots:

Example-1:

# First line
x <- 1:10
y1 <- (x*x)
plot(x, y1, type = "b", frame = FALSE, pch = 19, 
     col = "red", xlab = "x", ylab = "y")
# A second line
lines(x, y2, pch = 18, col = "blue", type = "b", lty = 2)
# Add a legend to the plot
legend("topleft", legend=c("Line 1", "Line 2"),
       col=c("red", "blue"), lty = 1:2, cex=0.8)

Example-2: As functions for different types

# Create Line Chart
# convert factor to numeric for convenience 
Orange$Tree <- as.numeric(Orange$Tree) 
ntrees <- max(Orange$Tree)

# get the range for the x and y axis 
xrange <- range(Orange$age) 
yrange <- range(Orange$circumference) 

# set up the plot 
plot(xrange, yrange, type="n", xlab="Age (days)",
   ylab="Circumference (mm)" ) 
colors <- rainbow(ntrees) 
linetype <- c(1:ntrees) 
plotchar <- seq(18,18+ntrees,1)

# add lines 
for (i in 1:ntrees) { 
  tree <- subset(Orange, Tree==i) 
  lines(tree$age, tree$circumference, type="b", lwd=1.5,
    lty=linetype[i], col=colors[i], pch=plotchar[i]) 
} 

# add a title and subtitle 
title("Tree Growth", "example of line plot")

# add a legend 
legend(xrange[1], yrange[2], 1:ntrees, cex=0.8, col=colors,
   pch=plotchar, lty=linetype, title="Tree")