March 17, 2017

General Concepts

Plotting systems in R (incompatible)

  • base
    • Easy and straightforward (in my opinion)
    • Start with plot (or similar) functions
    • Use annotation functions to add elements or modify
    • Can't go back once the plot is created
  • lattice
    • Useful for conditioning types of plots
    • Object oriented
    • Plots are created with one single function call
    • Intense preparation
  • ggplot2
    • Combine the advatages of both

Devices in R

  • Screen
  • Vector format files (e.g. pdf, svg)
  • Bitmap format files (e.g. png, jpeg, tiff)

Grammar of Graphics

  • Mapping (creating a blank "map")
  • Aesthetic (e.g. color, size)
  • Geometric (e.g. points, lines, bars)

Check R and ggplot2 versions

version
# "version.string" >= 3.1.0
packageVersion("ggplot2")
# >= 2.2.0
  • If your R version < 3.1.0, you may update your R on https://cloud.r-project.org.
  • If your ggplot2 version < 2.2.0 or doesn't exist, please update or install your ggplot2 with the instruction in the next slide.

Install and load ggplot2

install.packages("ggplot2", repos = "https://cloud.r-project.org")
# "repos" argument is optional
library(ggplot2)

Scatter Plot
(iris & mtcars datasets)

The structure of iris

str(iris)
'data.frame':   150 obs. of  5 variables:
 $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
 $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
 $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
 $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
 $ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...

g <- ggplot(aes(x = Petal.Length, y = Petal.Width), data = iris)
g <- g + geom_point(aes(color = Species)) +
  geom_smooth(method = "lm", color = "black")
g + labs(list(x = "Length of Petal", y = "Width of Petal",
              title = "My First Scatter Plot with ggplot2"))

Save the plot

ggsave("my_first_plot.png", width = 7, height = 7, dpi = 900)
# The file will be saved in your working directory unless specified
# 'plot = last_plot()' by default

The structure of mtcars

str(mtcars)
'data.frame':   32 obs. of  11 variables:
 $ mpg : num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
 $ cyl : num  6 6 4 6 8 6 8 4 4 6 ...
 $ disp: num  160 160 108 258 360 ...
 $ hp  : num  110 110 93 110 175 105 245 62 95 123 ...
 $ drat: num  3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...
 $ wt  : num  2.62 2.88 2.32 3.21 3.44 ...
 $ qsec: num  16.5 17 18.6 19.4 17 ...
 $ vs  : num  0 0 1 1 0 1 0 1 1 1 ...
 $ am  : num  1 1 1 0 0 0 0 0 0 0 ...
 $ gear: num  4 4 4 3 3 3 3 4 4 4 ...
 $ carb: num  4 4 1 1 2 1 4 2 2 4 ...

It's your turn!

Bar Plots
(airquality dataset)

The structure of airquality

str(airquality)
'data.frame':   153 obs. of  6 variables:
 $ Ozone  : int  41 36 12 18 NA 28 23 19 8 NA ...
 $ Solar.R: int  190 118 149 313 NA NA 299 99 19 194 ...
 $ Wind   : num  7.4 8 12.6 11.5 14.3 14.9 8.6 13.8 20.1 8.6 ...
 $ Temp   : int  67 72 74 62 56 66 65 59 61 69 ...
 $ Month  : int  5 5 5 5 5 5 5 5 5 5 ...
 $ Day    : int  1 2 3 4 5 6 7 8 9 10 ...

Data preparation

se_cal <- function(x) {sd(x, na.rm = TRUE)/sqrt(length(na.omit(x)))}
myair <- sapply(1:4,
                function(i){tapply(airquality[,i], airquality$Month,
                                   mean, na.rm = TRUE)})
colnames(myair) <- names(airquality)[1:4]
myair <- as.data.frame(as.table(myair))
se <- sapply(1:4,
             function(i){tapply(airquality[,i], airquality$Month,
                                se_cal)})
myair$SE <- as.data.frame(as.table(se))$Freq
names(myair) <- c("Month", "Variable", "Mean", "SE")

g <- ggplot(aes(x = Month, y = Mean), data = myair)
g <- g + geom_col(aes(fill = Variable), position = "dodge")
# geom_col() = geom_bar(stat = "identity")
g + geom_errorbar(aes(ymin = Mean - SE, ymax = Mean + SE, group = Variable),
                       position = position_dodge(0.9), width = 0.2)

Data for practice

myiris <- sapply(1:4,
                 function(i){tapply(iris[,i], iris$Species,
                                    mean, na.rm = TRUE)})
colnames(myiris) <- names(iris)[1:4]
myiris <- as.data.frame(as.table(myiris))
se <- sapply(1:4,
             function(i){tapply(iris[,i], iris$Species, se_cal)})
myiris$SE <- as.data.frame(as.table(se))$Freq
names(myiris) <- c("Species", "Variable", "Mean", "SE")

It's your turn!

Creating Facets

Revisit the first scatter plot
(theme_classic)

Faceting

g + facet_grid(. ~ Species)

It's your turn!

Extra Challenge

Data simulation

ID <- rep(1:20, each = 20)
age <- rep(c("Young", "Old"), each = 200)
sex <- rep(rep(c("Male", "Female"), each = 100), times = 2)
task <- rep(rep(c("A", "B"), each = 10), times = 20)
difficulty <- rep(1:10, times = 40)
simul <- data.frame(ID = ID,
                    age = factor(age, levels = c("Young", "Old")),
                    sex = factor(sex, levels = c("Male", "Female")),
                    task = factor(task, level = c("A", "B")),
                    difficulty = difficulty)
set.seed(1022)
simul$accuracy <- (rnorm(400, 80, 5) - 3*simul$difficulty -
  10*(as.numeric(simul$age)-1) +
  2*simul$difficulty*(as.numeric(simul$task)-1))/100

Come on challengers!

Resources

Thanks for your attention!
Happy plotting!