3  Descriptive Statistics and Figures

Week 3: Summarising data and producing figures with ggplot2

Before testing any hypothesis, you need to describe your data: where the centre is, how spread out the values are, and what the data look like. In this workshop you will learn which summary statistics suit which kinds of data, and how to build clear, publication-quality figures with ggplot2. Workshop materials are available in the GitHub repository ECS200.

TipLearning outcomes

By the end of this workshop you should be able to:

  1. Choose suitable measures of centre and spread for different types of variables.
  2. Explain the difference between a standard deviation, a standard error and a confidence interval.
  3. Calculate summary statistics for groups with group_by() and summarise().
  4. Build histograms, boxplots, dot plots and scatterplots with ggplot2, and polish them for a report.

Background

The right summary depends on the scale of the variable:

Scale Type Definition Examples Centre Spread
Nominal Categorical Named categories with no order Sex, species, habitat Mode Counts, proportions
Ordinal Categorical Categories with a natural order Life stage (egg, juvenile, adult), damage score 0–5 Median, mode Range, IQR
Interval Numeric Equal intervals, no true zero Temperature (°C), pH, dates Mean, median SD, SE, CI
Ratio Numeric Equal intervals and a true zero Length, mass, age, counts Mean, median SD, SE, CV, IQR, CI

When you design a data sheet, think about what type each column will be. Here is an example colour-coded by type: nominal, continuous, ordinal and binary.

Key terms used in this workshop:

Central tendency:

  • Mean: the average. Best for roughly symmetrical data.
  • Median: the middle value. Robust to outliers and skew.
  • Mode: the most frequent value (useful for categories).

Spread:

  • Standard deviation (SD): how spread out the data are around the mean.
  • Standard error (SE): SD / √n. How precisely the mean has been estimated.
  • 95% confidence interval (CI): a range that is likely to contain the true mean (mean ± about 2 × SE).
  • Coefficient of variation (CV): SD / mean. Compares variability between variables measured on different scales.
  • Interquartile range (IQR): the range of the middle 50% of the data (Q3 − Q1).
  • Variance: SD². The average squared distance from the mean.

CrashCourse Statistics has short videos on measures of central tendency and measures of spread if you would like a refresher.

Before we start

Code
# Week 3 workshop - Descriptive statistics
# Written by Nicholas Wu, 1234578, 11/03/2027

# install.packages("patchwork")  # run once in the console if needed

library(tidyverse)  # data wrangling and ggplot2
library(patchwork)  # combine several ggplots into one figure

# setwd("C:/Users/YOUR-NAME/Documents/ECS200")

Part 1: Descriptive statistics

The app below shows why it matters whether you plot the SD, SE or CI. Increase the sample size and see what happens to each.

The three error bars answer different questions:

Formula Question it answers When n increases When the true SD increases
SD \(\sqrt{\frac{\sum(x - \bar{x})^2}{n - 1}}\) How much do individual measurements vary? Stays about the same Gets wider
SE \(\frac{SD}{\sqrt{n}}\) How precisely do we know the mean? Shrinks Gets wider
95% CI \(\bar{x} \pm t \times SE\) Where is the true population mean likely to be? Shrinks, fastest at small n Gets wider

Increasing the sample size

  • SD stays about the same. The SD describes the spread of the population, and that does not change because you measured more individuals. With a larger sample, your estimate of the SD just gets closer to the true value (it jumps around less when you press Resample).
  • SE shrinks. The SE divides the SD by \(\sqrt{n}\). More data gives a more precise estimate of the mean, but with diminishing returns: to halve the SE you need four times as many samples (e.g. from 10 to 40).
  • The CI shrinks even faster at small n. The CI is the SE multiplied by a value from the t distribution. With very few samples, t is large (4.3 when n = 3) because we are unsure about the SD as well as the mean. As n grows, t drops towards about 2 (2.26 at n = 10, 1.98 at n = 100), so the 95% CI ends up at roughly 2 × SE.

Increasing the true SD

  • All three get wider in proportion. If individuals vary more, the data are more spread out (larger SD), and the mean is harder to pin down (larger SE and CI). Doubling the SD doubles all three bars.
  • The y-axis of the app rescales with the SD, so the bars may look similar. Read the numbers under the plot.

Why it matters

  • Use the SD when you want to show how variable the organisms or sites are (e.g. “lizards weighed 15.2 ± 2.1 g, mean ± SD”).
  • Use the SE or 95% CI when you want to show how precisely you have estimated the mean, or to compare groups. The CI is the easier one to interpret.
  • A small SE does not mean the data have little variation; it may just mean a large sample. This is why you must always state which one your error bars show.

App: standard deviation, standard error and confidence interval

Exercise 1 (5 min)

🧪 Summarise species 3 in this survey

Code
survey_data <- data.frame(
  site      = c("A", "A", "A", "B", "B", "B", "C", "C", "C"),
  plot      = c(1, 2, 3, 1, 2, 3, 1, 2, 3),
  species_1 = c(12, 7, 15, 4, 9, 6, 20, 18, 25),
  species_2 = c(5, 2, 1, 10, 7, 4, 3, 1, 0),
  species_3 = c(0, 3, 2, 6, 4, 5, 0, 1, 2),
  species_4 = c(8, 6, 3, 1, 4, 2, 10, 7, 5)
)
  • Calculate the mean, standard deviation and sample size of species_3.
  • Does a mean make sense for count data like these? What else could you report?
Show answer
Code
survey_data %>%
  dplyr::summarise(mean   = mean(species_3),
                   sd     = sd(species_3),
                   median = median(species_3),
                   n      = dplyr::n())
      mean       sd median n
1 2.555556 2.127858      2 9
Code
# mean = 2.56, SD = 2.13, n = 9. A mean of 2.56 individuals is not a possible
# count, but it is still a valid average. The median (2) and range (0 to 6)
# are also useful for small counts.

By groups

Most of the time you want summaries for each group, e.g. each site, species or treatment. Convert the data to long format, then use group_by().

Code
survey_long <- survey_data %>%
  tidyr::pivot_longer(cols      = species_1:species_4,
                      names_to  = "species",
                      values_to = "abundance")

# Mean, SD and sample size of abundance for each site and species
survey_summary <- survey_long %>%
  dplyr::group_by(site, species) %>%
  dplyr::summarise(mean = mean(abundance),
                   sd   = sd(abundance),
                   n    = dplyr::n(),
                   .groups = "drop") # remove the grouping afterwards

survey_summary
# A tibble: 12 × 5
   site  species    mean    sd     n
   <chr> <chr>     <dbl> <dbl> <int>
 1 A     species_1 11.3   4.04     3
 2 A     species_2  2.67  2.08     3
 3 A     species_3  1.67  1.53     3
 4 A     species_4  5.67  2.52     3
 5 B     species_1  6.33  2.52     3
 6 B     species_2  7     3        3
 7 B     species_3  5     1        3
 8 B     species_4  2.33  1.53     3
 9 C     species_1 21     3.61     3
10 C     species_2  1.33  1.53     3
11 C     species_3  1     1        3
12 C     species_4  7.33  2.52     3
Code
# Mean +/- SD for each species at each site
ggplot2::ggplot(survey_summary,
                ggplot2::aes(x = site, y = mean, ymin = mean - sd, ymax = mean + sd, colour = species)) +
  ggplot2::geom_pointrange(position = ggplot2::position_dodge(width = 0.6)) + # dodge so species don't overlap
  ggplot2::labs(x = "Site", y = "Abundance (mean ± SD)", colour = "Species") +
  ggplot2::theme_classic()

Part 2: Figures with ggplot2

The “gg” in ggplot2 stands for grammar of graphics. You build a plot in layers, joined with +:

  1. ggplot2::ggplot(data, ggplot2::aes(x = ..., y = ...)) sets the data and which columns go on which axis (the aesthetics).
  2. geom_...() layers draw the data: points, lines, boxes, bars.
  3. labs(), scale_...(), theme_...() and facet_...() adjust labels, colours, the overall look and panels.

Before plotting, decide which variable is the independent (predictor, on the x-axis) and which is the dependent (response, on the y-axis) variable.

Plot types

Which plot to use depends on the types of variables you have:

We will use the clean sugar maple data from Weeks 1 and 2 to compare stem length between the calcium-treated (W1) and untreated (Reference) watersheds.

Code
plant_data <- readr::read_csv("data/plant_calcium_task.csv") %>%
  dplyr::mutate(watershed     = dplyr::if_else(watershed == "W2", "W1", watershed),
                watershed     = factor(watershed),
                total_mass_mg = (leaf_dry_mass + stem_dry_mass) * 1000) %>%
  dplyr::filter(stem_dry_mass < 1)

Polishing plots

Assessment

Task to complete before the end of the workshop.

week03_assessment.R

Continue in the script you started in Week 2 (with total_mass_mg), under the header “Week 3 workshop - Descriptive statistics”.

  1. Plot the distribution of total_mass_mg. Is it symmetrical or skewed?
  2. Based on your answer to Q1, choose suitable measures of centre and spread, and calculate them, together with the sample size, for each combination of watershed and year. Explain your choice in a comment.
  3. What are the centre, spread and sample size for W1 seedlings in 2003? Are they similar for W1 seedlings in 2004? If not, describe the difference.
  4. Make a publication-ready figure that shows the raw data and your chosen centre and spread for each watershed and year. Use colour, label the axes with units, and use facet_wrap() for the years.
  5. In one or two sentences, describe what the figure shows about the effect of calcium on seedling mass.

The figure could look something like either of these:

Submit one R script (.R) before the end of the class. Write your answers to written questions as # comments next to the code that produced them.

Score What it looks like
0 No submission or no attempt.
0.25 Submitted, but a very poor attempt (e.g. incomplete, or lots of gaps).
0.5 Most questions answered, or all answered but most annotations missing.
0.75 All questions answered, but some annotations missing or some answers incorrect.
1 Everything completed, with annotations on all code so the marker can follow it.

Tip: an annotation is a short # comment that says what the line does and why. For example: # remove the one plant with a stem dry mass of 7.4 g (data entry error).

For the adventurous

pie_crab.csv

pie_crab.csv contains carapace widths (size, mm) of Atlantic marsh fiddler crabs (Minuca pugnax) from 13 salt marshes on the east coast of the USA, collected to test Bergmann’s rule (animals are larger in colder places, at higher latitudes). Other columns: latitude, site, mean air and water temperature (air_temp, water_temp) and their SDs.

Atlantic marsh fiddler crab (Minuca pugnax).
  1. Run a quality check. Are there missing values or duplicated rows? Are the duplicates real?
  2. Calculate the mean, SD and sample size of size for each site. Which site has the largest crabs, and which has the fewest crabs measured?
  3. Plot carapace width against latitude, showing the raw data and the site means (coloured by air temperature). What pattern do you see? You will analyse these data in Week 7.

Additional resources

An example from the Coding Club figure beautification tutorial.