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

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

ggplot2

In [5]:
library(tidyverse)
── Attaching packages ─────────────────────────────────────── tidyverse 1.2.1 ──
✔ ggplot2 2.2.1     ✔ purrr   0.2.5
✔ tibble  1.4.2     ✔ dplyr   0.7.5
✔ tidyr   0.8.1     ✔ stringr 1.3.1
✔ readr   1.1.1     ✔ forcats 0.3.0
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag()    masks stats::lag()

ggplto2 only works on data.frame or similar objects

In [6]:
df <- tibble(x=x, y=y)
In [7]:
head(df)
xy
0.0078876791.3998233
0.0097868651.0518361
0.0124356111.1777531
0.0134983440.6454949
0.0248605461.0486680
0.0250395191.3167181
In [8]:
ggplot(df, aes(x=x, y=y)) +
geom_point() +
geom_line(aes(x=x, y=predict(m), color="red")) +
labs(title="ggplot2")
Data type cannot be displayed:
../_images/cliburn_R_Graphics_Overview_13_1.png

lattice

For more examples, see Getting Started with Lattice Graphics

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