R Graphics

R Graphics Systems

There are 3 different grpahcis systems widely used in R - base, lattice and ggplot2. We will focus on ggplot2 because it provides the most logical approach to plot constructin using a grammar of graphics.

Base

[1]:
n <- 100
x <- sort(runif(n))
y <- x^2 + x + 1 + 0.2*rnorm(n)
[2]:
m <- lm(y ~ I(x^2))
[3]:
options.orig <- options(repr.plot.width=6, repr.plot.height=4)
[4]:
plot(x, y, main="Base Graphics")
lines(x, predict(m), col = "red", lwd = 2)
../_images/cliburn_R06_Graphics_Overview_7_0.png

ggplot2

[5]:
library(tidyverse)
Registered S3 methods overwritten by 'ggplot2':
  method         from
  [.quosures     rlang
  c.quosures     rlang
  print.quosures rlang
── Attaching packages ─────────────────────────────────────── tidyverse 1.2.1 ──
 ggplot2 3.1.1      purrr   0.3.2
 tibble  2.1.2      dplyr   0.8.1
 tidyr   0.8.3      stringr 1.4.0
 readr   1.3.1      forcats 0.4.0
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
 dplyr::filter() masks stats::filter()
 dplyr::lag()    masks stats::lag()

ggplto2 only works on data.frame or similar objects

[6]:
df <- tibble(x=x, y=y)
[7]:
head(df)
A tibble: 6 × 2
xy
<dbl><dbl>
0.025977200.8526721
0.039396770.9947642
0.049151260.9809143
0.049202001.1198401
0.056099141.0031721
0.066697881.3603442
[8]:
ggplot(df, aes(x=x, y=y)) +
geom_point() +
geom_line(aes(x=x, y=predict(m), color="red")) +
labs(title="ggplot2")
../_images/cliburn_R06_Graphics_Overview_13_0.png

lattice

For more examples, see Getting Started with Lattice Graphics

[9]:
library(lattice)
[10]:
xyplot(y ~ x,
       main = "Lattice Graphics",
       panel = function(x, y, ...) {
             panel.xyplot(x, y, ...)
             panel.lines(x, predict(m), col.line = "red")
         }
       )
../_images/cliburn_R06_Graphics_Overview_16_0.png