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)
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)
x | y |
---|---|
0.007887679 | 1.3998233 |
0.009786865 | 1.0518361 |
0.012435611 | 1.1777531 |
0.013498344 | 0.6454949 |
0.024860546 | 1.0486680 |
0.025039519 | 1.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:
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: