ggplot22026-02-19
ggplot2
Create elegant data visualizations using the Grammar of Graphics
ggplot2
ggplot2is a system for declaratively creating graphics, based on The Grammar of Graphics. You provide the data, tell ggplot2 how to map variables to aesthetics, what graphical primitives to use, and it takes care of the details.
ggplot2Wilkinson (2005) created the grammar of graphics to describe the fundamental features that underlie all statistical graphics. The grammar of graphics is an answer to the question of what is a statistical graphic? ggplot2 (Wickham 2009) builds on Wilkinson’s grammar by focussing on the primacy of layers and adapting it for use in R. In brief, the grammar tells us that a graphic maps the data to the aesthetic attributes (colour, shape, size) of geometric objects (points, lines, bars). The plot may also include statistical transformations of the data and information about the plot’s coordinate system. Facetting can be used to plot for different subsets of the data. The combination of these independent components are what make up a graphic.
ggplot2 BasicsIt’s hard to succinctly describe how
ggplot2works because it embodies a deep philosophy of visualisation. However, in most cases you start withggplot(), supply a dataset and aesthetic mapping (withaes()). You then add on layers (likegeom_point()orgeom_histogram()), scales (likescale_colour_brewer()), faceting specifications (likefacet_wrap()) and coordinate systems (likecoord_flip()).
ggplot2 Basicsggplot()data, so you can (but don’t have to) specify that.ggplot().ggplot2 Basicsmapping, which you use to define the aesthetics of your plot using the function aes().
ggplot2 Basicsggplot(), all layers and options are added to the plot using the + operator.ggplot2 Basicsstarwars %>%
filter(hair_color %in% c("blond", "brown", "black", "none"),
!is.na(mass)) %>%
ggplot(aes(x = height, y = mass, color = hair_color)) +
geom_point() +
xlab("Height (cm)") +
ylab("Mass (kg)") +
ggtitle("Mass by Height and Hair Color",
subtitle = "in the Star Wars universe") +
scale_color_manual(name = "Hair Color",
breaks = c("blond", "brown", "black", "none"),
values = c("gold", "brown", "black", "gray"))ggplot2 Basicsstarwars %>%
filter(hair_color %in% c("blond", "brown", "black", "none"),
!is.na(mass)) %>%
ggplot(aes(x = height, y = mass, color = hair_color)) +
geom_point() +
xlab("Height (cm)") +
ylab("Mass (kg)") +
ggtitle("Mass by Height and Hair Color",
subtitle = "in the Star Wars universe") +
scale_color_manual(name = "Hair Color",
breaks = c("blond", "brown", "black", "none"),
values = c("gold", "brown", "black", "gray")) +
facet_wrap(~ hair_color) +
theme_bw() +
theme(text = element_text(size = 16))ggplot2 Cheatsheet