Unit 07.00: Data, mapping, layer
You are not choosing a chart type. You are saying which column controls which visual property, and then how to draw it.
Data, mapping, layer
Every ggplot is the same three statements. Data: the table. Mapping: which column becomes the x position, the y position, the colour, the size. Layer: the geom that draws it.
This is why ggplot2 feels different from a chart menu. A menu asks 'bar or line?'; the grammar asks what the picture should mean, and the geom follows from that. Changing only the geom gives a completely different chart from the same description.
Layers add with +. Two geoms on one mapping — points on top of a line, say — is simply two layers, not a special chart type.
This block builds one plot and inspects the object it made.
suppressPackageStartupMessages(library(ggplot2))
visits <- data.frame(ward = c("North", "South", "East", "West"),
visits = c(412, 388, 502, 331),
staffed = c(TRUE, TRUE, FALSE, TRUE))
# Every ggplot is the same three sentences: data, mapping, layer.
p <- ggplot(data = visits, # 1. the data
mapping = aes(x = ward, y = visits)) + # 2. columns -> visual properties
geom_col() # 3. how to draw it
cat("Layers in this plot:", length(p$layers), "\n")
cat("Mapped aesthetics :", paste(names(p$mapping), collapse = ", "), "\n\n")
# Change only the layer and you have a different chart from the same sentence.
q <- ggplot(visits, aes(x = ward, y = visits)) + geom_point(size = 3)
cat("Same data and mapping, geom_point instead of geom_col.\n")
f <- file.path(tempdir(), "grammar.png")
ggsave(f, p, width = 4, height = 3, dpi = 100)
cat("Saved:", basename(f), file.size(f), "bytes\n")
cat("\nYou are not choosing a chart type. You are describing a mapping.\n")
The plot has 1 layer and maps x and y. That is the whole specification: a data frame, two mappings, one geom. Swapping geom_col() for geom_point() produces a different chart from an otherwise identical description. The saved file confirms the object is a real plot and not just a preview.
The mistake this prevents
The mistake is thinking in chart types and hunting for the function that makes one. It leads to fighting the library whenever you want something slightly unusual, which the grammar handles as another layer.
Takeaway
Describe the mapping first — which column is x, which is y, which is colour — and pick the geom afterwards. Build up with + one layer at a time and look at the plot after each.
