Intermediate Data Visualization with ggplot2
Rick Scavetta
Founder, Scavetta Academy
# Plot
p <- ggplot(msleep2, aes(bodywt_log,
brainwt_log)) +
geom_point(alpha = 0.6, shape = 16) +
coord_fixed()
p
p +
facet_grid(rows = vars(vore))
p +
facet_grid(rows = vars(vore))
p +
facet_grid(rows = vars(vore))
Two typical problems with facets:
p +
facet_grid(rows = vars(vore))
Solutions:
# Default is to label the value
p +
facet_grid(rows = vars(vore),
labeller = label_value)
# Print variable name also
p +
facet_grid(rows = vars(vore),
labeller = label_both)
p +
facet_grid(rows = vars(vore,
conservation))
p +
facet_grid(rows = vars(vore,
conservation),
labeller = label_context)
p +
facet_grid(rows = vars(vore),
cols = vars(conservation),
labeller = label_context)
p +
facet_grid(rows = vars(vore),
cols = vars(conservation))
msleep2$conservation <- fct_recode(msleep2$conservation,
Domesticated = "domesticated",
`Least concern` = "lc",
`Near threatened` = "nt",
Vulnerable = "vu",
Endangered = "en")
msleep2$vore = fct_recode(msleep2$vore,
Carnivore = "carni",
Herbivore = "herbi",
Insectivore = "insecti",
Omnivore = "omni")
# Plot
p <- ggplot(msleep2, aes(bodywt_log,
brainwt_log)) +
geom_point(alpha = 0.6, shape = 16) +
coord_fixed()
p +
facet_grid(rows = vars(vore),
cols = vars(conservation))
# Change order of levels:
msleep2$conservation = fct_relevel(msleep2$conservation,
c("Domesticated",
"Least concern",
"Near threatened",
"Vulnerable",
"Endangered"))
Intermediate Data Visualization with ggplot2