Crash Courses · Masters
Visualization with ggplot2
Build publication-quality charts using ggplot2's grammar of graphics — scatter plots, histograms, box plots, bar charts, and faceted panels.
18 min read+180 XP on completionCert: R Crash Course
Tap any word in the text below to start reading from there.
Visualization with ggplot2
Installation and the Core Pattern
install.packages("ggplot2") # once
library(ggplot2)Every ggplot2 chart follows the same pattern:
ggplot(data = your_data, aes(x = col1, y = col2)) + # setup
geom_point() + # draw points
labs(title = "Title") + # labels
theme_minimal() # appearance---
Scatter Plot
# Built-in mtcars dataset: fuel efficiency vs weight
ggplot(mtcars, aes(x = wt, y = mpg, color = factor(cyl), size = hp)) +
geom_point(alpha = 0.8) +
scale_color_manual(values = c("4" = "#2196F3", "6" = "#FF9800", "8" = "#F44336")) +
labs(
title = "Fuel Efficiency vs. Weight",
subtitle = "Colored by cylinders, sized by horsepower",
x = "Weight (1000 lbs)",
y = "Miles per Gallon",
color = "Cylinders",
size = "Horsepower"
) +
theme_minimal(base_size = 13)---
Histogram
# Distribution of mpg values
ggplot(mtcars, aes(x = mpg)) +
geom_histogram(bins = 10, fill = "#2196F3", color = "white", alpha = 0.8) +
geom_vline(aes(xintercept = mean(mpg)), color = "red", linetype = "dashed", linewidth = 1) +
annotate("text", x = mean(mtcars$mpg) + 1, y = 7,
label = paste("Mean:", round(mean(mtcars$mpg), 1)),
color = "red", hjust = 0) +
labs(title = "Distribution of Fuel Efficiency", x = "MPG", y = "Count") +
theme_classic()---
Bar Chart
library(dplyr)
# Count cars by cylinder
cyl_counts <- mtcars %>%
count(cyl) %>%
mutate(cyl = factor(cyl))
ggplot(cyl_counts, aes(x = cyl, y = n, fill = cyl)) +
geom_col(show.legend = FALSE) +
geom_text(aes(label = n), vjust = -0.5, fontface = "bold") +
scale_fill_brewer(palette = "Blues") +
labs(title = "Cars by Number of Cylinders", x = "Cylinders", y = "Count") +
theme_minimal()---
Box Plot
ggplot(mtcars, aes(x = factor(cyl), y = mpg, fill = factor(cyl))) +
geom_boxplot(outlier.shape = 21, outlier.size = 3, alpha = 0.8) +
geom_jitter(width = 0.15, alpha = 0.5, size = 2) + # show individual points
scale_fill_brewer(palette = "Set2", guide = "none") +
labs(
title = "MPG Distribution by Cylinder Count",
x = "Number of Cylinders",
y = "Miles per Gallon"
) +
theme_bw()---
Line Chart with Multiple Series
# Simulated time series
set.seed(42)
time_data <- data.frame(
week = rep(1:12, 3),
revenue = c(
cumsum(rnorm(12, 100, 15)),
cumsum(rnorm(12, 90, 20)),
cumsum(rnorm(12, 110, 10))
),
product = rep(c("Laptop", "Phone", "Monitor"), each = 12)
)
ggplot(time_data, aes(x = week, y = revenue, color = product, group = product)) +
geom_line(linewidth = 1.2) +
geom_point(size = 2.5) +
scale_color_brewer(palette = "Dark2") +
labs(title = "Weekly Revenue by Product", x = "Week", y = "Cumulative Revenue ($)") +
theme_minimal() +
theme(legend.position = "bottom")---
facet_wrap() — Small Multiples
# Separate scatter plot per cylinder count
ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point(color = "#2196F3", size = 2.5, alpha = 0.7) +
geom_smooth(method = "lm", se = TRUE, color = "#F44336") +
facet_wrap(~cyl, labeller = label_both) +
labs(title = "MPG vs Weight: Faceted by Cylinders") +
theme_bw()---
Saving Plots
# Save the last plot
ggsave("mpg_analysis.png", width = 8, height = 6, dpi = 300)
# Save a specific plot object
p <- ggplot(mtcars, aes(x = mpg)) + geom_histogram(bins = 10)
ggsave("histogram.pdf", plot = p, width = 6, height = 4)---
Customizing Themes
# A fully custom theme
my_theme <- theme_minimal(base_size = 12) +
theme(
plot.title = element_text(face = "bold", size = 14, hjust = 0),
plot.subtitle = element_text(color = "grey50"),
panel.grid.minor = element_blank(),
axis.line = element_line(color = "grey70"),
legend.position = "bottom"
)
ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point(color = "#2196F3") +
labs(title = "Custom Theme Example", subtitle = "Clean, minimal style") +
my_themeReading progress
0% read
In this module
Grammar of Graphics
aes()
geom_()
facet_wrap()
0%