Lecture 1.3 - Stats 130 - R Graphics and More on R Markdown

1. Simple graphics in R

Plotting

_ plot(x): plot x (y-axis) versus index number (x-axis) in a new window

Plotting parameters

These can be added as arguments to plot, lines, image, etc. For help see par.

Nice Simple graphics with R

Reference: https://www.harding.edu/fmccown/r/

LINE CHARTS

# Define the cars vector with 5 values
cars <- c(1, 3, 6, 4, 9)

# Graph the cars vector with all defaults
plot(cars)

plot of chunk unnamed-chunk-1

plot(cars, type = "o", col = "blue", main = "Autos")

plot of chunk unnamed-chunk-1

Now let's add a red line for trucks and specify the y-axis range directly so it will be large enough to fit the truck data:

# Define 2 vectors
cars <- c(1, 3, 6, 4, 9)
trucks <- c(2, 5, 4, 5, 12)

# Graph cars using a y axis that ranges from 0 to 12
plot(cars, type = "o", col = "blue", ylim = c(0, 12))

# Graph trucks with red dashed line and square points
lines(trucks, type = "o", pch = 22, lty = 2, col = "red")

# Create a title with a red, bold/italic font
title(main = "Autos", col.main = "red", font.main = 4)

# Create a legend in the upper left corner
legend("topleft", c("cars", "trucks"), cex = 0.8, col = c("blue", "red"), pch = 21:22, 
    lty = 1:2)

plot of chunk unnamed-chunk-2

On your own: STUDY BAR CHARTS, PIE CHART, HISTOGRAMS, DOTCHARTS from

Reference: https://www.harding.edu/fmccown/r/

YOUR TURN - In-class 1.3

Overlay the graph with the third auto type for SUVs. Graph SUVs with black dashed line and square points. Create a title with a blue, bold/italic font. Create a legend in the upper left corner.

2. R Markdown (continued) - Block, R code chunk and Inline R code.

2.1 Block Code

Text included in a block will be shown in a block. R code included in a block is treated as text and won't be evaluated.

summary(cars$dist)
summary(cars$speed)

2.2 R code chunk

This is the structure of an R code chunk, similar to the block but with curly brackets around letter r

R code will be evaluated and printed when included in chunks. Example:

  # Define the cars vector with 5 values
  trucks <- c(1, 3, 6, 4, 9, 12)

  # Graph trucks using blue points overlayed by a line
  plot(trucks, type = "o", col = "blue")

  # Create a title
  title(main = "Autos")

plot of chunk unnamed-chunk-4

2.3 Inline R code

To embed R code inline with text, use the single quotation marks and include the lower case letter _r_:  `r `

Example 1: My favorite number is 3.1416.

Example 2 : The names of the variables in the dataset mtcars are mpg, cyl, disp, hp, drat, wt, qsec, vs, am, gear, carb.

Next week:

2. Graphics with ggplot2 and Text Output in R Markdown