# Your first ggplot: data, aes and geom
# https://tidyecology.com/posts/your-first-ggplot/
#
# The R code of this Tidy Ecology tutorial, chunk by chunk, in the order of the post.
# Run it top to bottom in a fresh R session. Code the post shows but does not run
# is commented out. The prose, and the numbers it quotes, are in the post itself.
# Post last modified: 2026-10-15

## ---- page-canvas ----
# Site chrome only: draw on the page colour instead of white, so the figures below
# sit flush on the page. Nothing else about the default theme changes, and none of
# the code shown in this post depends on it.
library(ggplot2)
theme_set(theme_grey() + theme(plot.background = element_rect(fill = "#f5f4ee", colour = NA)))

## ---- data ----
library(ggplot2)

counts <- data.frame(
  species = c("Festuca", "Trifolium", "Plantago", "Achillea", "Bromus"),
  individuals = c(42, 7, 3, 5, 11)
)
counts

## ---- fig-first ----
ggplot(counts, aes(x = species, y = individuals)) +
  geom_col()

## ---- pieces ----
# ggplot(data, aes(mapping)) + geom_something()
# #      ^data  ^which columns   ^what marks

## ---- fig-nogeom ----
ggplot(counts, aes(x = species, y = individuals))

## ---- fig-wrong ----
ggplot(counts, aes(x = species, y = individuals, fill = "blue")) +
  geom_col()

## ---- fig-right ----
ggplot(counts, aes(x = species, y = individuals)) +
  geom_col(fill = "#2c5f8a")

## ---- fig-mapped ----
ggplot(counts, aes(x = species, y = individuals, fill = species)) +
  geom_col() +
  scale_fill_brewer(palette = "Dark2")

## ---- fig-swap ----
ggplot(counts, aes(x = species, y = individuals)) +
  geom_point(size = 3)

## ---- fig-ylim ----
ggplot(counts, aes(x = species, y = individuals)) +
  geom_col() +
  ylim(0, 20)

## ---- fig-coord ----
ggplot(counts, aes(x = species, y = individuals)) +
  geom_col() +
  coord_cartesian(ylim = c(0, 20))

## ---- zoom-medians ----
count_box <- ggplot(counts, aes(y = individuals)) + geom_boxplot()
median_plain <- layer_data(count_box)$middle
median_ylim <- layer_data(count_box + ylim(0, 20))$middle
median_coord <- layer_data(count_box + coord_cartesian(ylim = c(0, 20)))$middle
c(no_limits = median_plain, with_ylim = median_ylim, with_coord_cartesian = median_coord)

## ---- removed-rows-checks ----
# Checks behind the sentences in this section: the page stops building if a newer ggplot2 differs.
# drawn_warnings() draws a plot without showing it and keeps the warnings it raises.
drawn_warnings <- function(plot) { found <- character(0); withCallingHandlers(ggplotGrob(plot), warning = function(w) { found <<- c(found, conditionMessage(w)); invokeRestart("muffleWarning") }); found }
removed_rows <- function(plot) sum(as.numeric(sub("^Removed ([0-9]+) row.*$", "\\1", grep("^Removed [0-9]+ row", drawn_warnings(plot), value = TRUE))))
bars <- ggplot(counts, aes(species, individuals)) + geom_col()
zoom <- coord_cartesian(ylim = c(0, 20))
kept <- counts$individuals[counts$individuals <= 20]
logged <- ggplot(data.frame(site = c("A", "B", "C"), value = c(0, 3, 5)), aes(site, value)) + scale_y_log10()
one_site <- ggplot(data.frame(site = "A", value = counts$individuals), aes(site, value))
bar_warn <- drawn_warnings(bars + ylim(0, 20))
box_warn <- drawn_warnings(count_box + ylim(0, 20))
old_gg <- packageVersion("ggplot2") < "3.5.0"
stopifnot(median_ylim == median(kept), median_coord == median(counts$individuals), median_plain == median(counts$individuals),
  any(grepl("^Removed 1 row.*missing", bar_warn)), !any(grepl("non-finite", bar_warn)), any(grepl("^Removed 1 row.*non-finite", box_warn)),
  !old_gg || any(startsWith(bar_warn, "Removed 1 rows containing missing values")), !old_gg || any(startsWith(box_warn, "Removed 1 rows containing non-finite values")),
  old_gg || any(startsWith(bar_warn, "Removed 1 row containing missing values or values outside the scale range")),
  removed_rows(ggplot(data.frame(block = c("a", "b"), m = c(38, 42.25)), aes(block, m)) + geom_col() + ylim(36, 44)) == 2)
stopifnot(removed_rows(bars + ylim(0, 20)) == 1, length(drawn_warnings(bars + zoom)) == 0, removed_rows(bars + ylim(5, 50)) == nrow(counts),
  length(drawn_warnings(count_box + zoom)) == 0, identical(layer_data(count_box + zoom)$outliers[[1]], 42), identical(ylim(0, 20)$limits, c(0, 20)),
  removed_rows(ggplot(data.frame(value = c(NA, 3, 5)), aes(y = value)) + geom_boxplot()) == 1, inherits(ylim(0, 20), "ScaleContinuousPosition"),
  removed_rows(logged + geom_boxplot()) == 1, removed_rows(logged + geom_point()) == 0, identical(ylim(0, 20)$oob(c(-1, 5, 25), c(0, 20)), c(NA, 5, NA)),
  all.equal(suppressWarnings(layer_data(one_site + stat_summary(fun = mean, geom = "point") + ylim(0, 20))$y), mean(kept)))
