ggplot2 is not a plotting library with a function per chart type. It is an implementation of the grammar of graphics: a chart is built by combining independent parts, and because they are independent, charts nobody wrote a function for are still one line away.
The parts are data (a data frame, in long form), aesthetics (which column maps to which visual property - x, y, colour, size, shape, alpha), geoms (the marks: points, lines, bars, boxes), scales (how a data value becomes a pixel or a colour), facets (splitting into panels by a variable), coordinates, and theme (everything not about the data). You combine them with +.
The distinction that causes the most confusion is mapping against setting. Inside aes() you are mapping a column to a property, and ggplot2 will build a legend for it. Outside aes() you are setting a constant. aes(colour = "blue") does not make the points blue - it maps them all to a one-level category which ggplot2 then colours red, and adds a legend saying "blue". colour = "blue", outside aes(), is what you meant.
Geoms worth knowing first. geom_point() for scatter, geom_line() for a series over time, geom_col() for bars when you have the values and geom_bar() when you want ggplot2 to count rows for you, geom_histogram() for a distribution, geom_boxplot() for distributions compared across groups, and geom_smooth() to add a trend line with a confidence band.
Facets are the feature that pays for learning the grammar. facet_wrap(~ group) turns one chart into one small chart per level of group, on shared axes, in a single line. Comparing eight groups on one chart is a mess; comparing them as eight panels is immediate.
Getting it out. ggsave() writes the last plot, and takes width, height and dpi in real units. Specify them. A chart saved at the default size has text sized for a different chart than the one you are putting in a document, which is why ggplot2 output so often arrives with unreadable axis labels.
library(ggplot2)
library(dplyr)
# mpg ships with ggplot2: 234 cars, 11 columns.
# ---- The three parts every plot has ----------------------------------
ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) + # data + aes
geom_point() # a geom
# ---- Mapping vs setting: the usual confusion -------------------------
ggplot(mpg, aes(displ, hwy)) +
geom_point(aes(colour = class)) # MAP a column -> legend appears
ggplot(mpg, aes(displ, hwy)) +
geom_point(colour = "steelblue") # SET a constant -> no legend
# ggplot(mpg, aes(displ, hwy)) + geom_point(aes(colour = "steelblue"))
# maps every point to a one-level category called "steelblue", draws
# them all RED, and adds a legend. This is the mistake, every time.
# ---- Layers stack, and each may have its own data or aes -------------
ggplot(mpg, aes(displ, hwy)) +
geom_point(alpha = 0.6) +
geom_smooth(method = "lm", se = TRUE) + # a fit, with its band
labs(
title = "Larger engines use more fuel",
subtitle = "Each point is one car model",
x = "Engine displacement (litres)",
y = "Highway miles per gallon",
caption = "Source: ggplot2::mpg"
)
# ---- The plots you will actually build -------------------------------
# Bars from values you already have:
mpg |>
summarise(n = n(), .by = class) |>
ggplot(aes(x = reorder(class, -n), y = n)) + # reorder: sort them
geom_col(fill = "steelblue")
# Bars where ggplot2 counts the rows for you:
ggplot(mpg, aes(class)) + geom_bar()
# A distribution:
ggplot(mpg, aes(hwy)) + geom_histogram(bins = 30, fill = "grey30")
# Distributions compared - and the points over the top, because a
# boxplot hides how many observations each box is made of:
ggplot(mpg, aes(class, hwy)) +
geom_boxplot(outlier.shape = NA) +
geom_jitter(width = 0.2, alpha = 0.4)
# A series over time needs group when there is more than one line:
# ggplot(ts, aes(date, value, colour = region, group = region)) + geom_line()
# ---- Facets: one line, many panels -----------------------------------
ggplot(mpg, aes(displ, hwy)) +
geom_point() +
facet_wrap(~ class) # one panel per class
ggplot(mpg, aes(displ, hwy)) +
geom_point() +
facet_grid(drv ~ cyl) # rows ~ columns
# free scales when the panels differ wildly in magnitude:
# facet_wrap(~ class, scales = "free_y")
# ---- Scales and theme ------------------------------------------------
ggplot(mpg, aes(displ, hwy, colour = class)) +
geom_point(size = 2) +
scale_x_continuous(limits = c(1, 7), breaks = seq(1, 7, 1)) +
scale_y_continuous(labels = scales::comma) +
scale_colour_brewer(palette = "Set2") + # a colourblind-safe set
theme_minimal(base_size = 12) +
theme(
legend.position = "bottom",
plot.title = element_text(face = "bold", size = 16),
panel.grid.minor = element_blank()
)
# ---- Saving: always state the size -----------------------------------
p <- ggplot(mpg, aes(displ, hwy)) + geom_point()
ggsave("plot.png", p, width = 8, height = 5, dpi = 300)
ggsave("plot.pdf", p, width = 8, height = 5) # vector, for print
# The default size is not your document's size, which is why ggplot2
# output so often lands with text too small to read. Say what you want.
Discussion
No questions on this topic yet. Sign in to ask the first one.