Skip to content
AgileLogics
7 min read

Data Visualization with ggplot2

Prerequisites: dplyr: mutate, summarise, and group_by

ggplot2 builds charts from layers, following a "grammar of graphics": every chart is data, mapped to visual properties (aesthetics), drawn with geometric objects (points, lines, bars).

Your first chart

library(ggplot2)

ggplot(mpg, aes(x = displ, y = hwy)) +
  geom_point()
  • mpg is a dataset included with ggplot2 (fuel economy for 234 cars).
  • aes(x = displ, y = hwy) maps engine size to the x-axis and highway miles per gallon to the y-axis.
  • geom_point() draws a point for each row — a scatter plot.
  • Layers are added with + (not |>).

The chart appears in RStudio's Plots pane. It shows that cars with bigger engines tend to use more fuel.

Mapping more variables

ggplot(mpg, aes(x = displ, y = hwy, colour = class)) +
  geom_point(size = 2, alpha = 0.7) +
  geom_smooth(aes(group = 1), method = "lm", se = FALSE, colour = "grey40") +
  labs(
    title = "Bigger engines, lower fuel economy",
    x = "Engine displacement (litres)",
    y = "Highway miles per gallon",
    colour = "Car class"
  ) +
  theme_minimal()
  • colour = class inside aes() colours points by car type, with a legend added automatically.
  • Settings outside aes() — size = 2, alpha = 0.7 — apply to all points, rather than depending on data.
  • geom_smooth(method = "lm") adds a straight trend line.
  • labs() sets the title and axis labels; theme_minimal() gives a clean look.

The chart types you'll use most

Question Geom
Relationship between two numbers geom_point()
Change over time geom_line()
Compare amounts across groups geom_col() / geom_bar()
Distribution of one number geom_histogram(), geom_density()
Distribution across groups geom_boxplot(), geom_violin()
library(dplyr, warn.conflicts = FALSE)

mpg |>
  count(class) |>
  ggplot(aes(x = reorder(class, n), y = n)) +
  geom_col(fill = "steelblue") +
  coord_flip() +
  labs(x = NULL, y = "Number of cars")

This counts cars per class with dplyr and draws a horizontal bar chart, with bars sorted by size (reorder). dplyr and ggplot2 are designed to be used together like this.

Saving

ggsave("hwy_vs_displ.png", width = 7, height = 5, dpi = 300)

ggsave saves the most recent chart; the extension decides the format (.png, .pdf, .svg).

Common mistakes

  • Using |> between layers instead of +.
  • Putting a fixed colour inside aes() — aes(colour = "blue") creates a legend entry called "blue" with a default colour. Set fixed values outside aes().