Lesson 4 Exercise Questions: ggplot2
This exercise questions are meant to test your learning following Lesson 4: Recommendations and Tips for Creating Effective Plots with ggplot2. To approach these questions, you will need to understand how to find help.
Start by loading ggplot2 and patchwork.
if (!requireNamespace("ggplot2", quietly = TRUE)) install.packages("ggplot2")
if (!requireNamespace("patchwork", quietly = TRUE)) install.packages("patchwork")
library(ggplot2)
library(patchwork)
Q1. Write a function plot_mpg_by_cyl(df) that plots a box plot of mpg vs cyl colored by gear. Test on mtcars.
Q1: Solution
plot_mpg_by_cyl <- function(df) {
ggplot(df) +
geom_boxplot(aes(x = factor(cyl), y = mpg, fill = factor(gear))) +
labs(x = "cyl", y = "mpg", color = "gear") +
theme_minimal()
}
plot_mpg_by_cyl(mtcars)

Q2. Write scatter_plot(df, x, y, color) that creates a scatter plot using column names for x, y, and color. Test on iris with Sepal.Length, Petal.Length, Species.
Q2: Solution
scatter_plot <- function(df, x, y, color) {
ggplot(df) +
geom_point(aes(x = {{x}}, y = {{y}}, color = {{color}})) +
theme_minimal()
}
scatter_plot(iris, Sepal.Length, Petal.Length, Species)

Q3. Write facet_histogram(df, variable, facet_by, bins = 30) that draws a histogram of a numeric variable and facet_wraps by facet_by. The function should also accept a bins argument. Test on diamonds with price by cut.
Q3: Solution
facet_histogram <- function(df, variable, facet_by, bins = 30) {
ggplot(df) +
geom_histogram(aes(x = {{variable}}), bins = bins,
color = "white") +
facet_wrap(vars({{facet_by}})) +
labs(x= stringr::str_to_sentence(rlang::englue("{{variable}}")),
y = "Count") +
theme_minimal()
}
facet_histogram(ggplot2::diamonds, price, cut, bins = 40)

Q4. Challenge Question: Define a function plot_relationship(df, x, y, method = "point") that:
-
uses
geom_point()when method = "point", -
uses
geom_point()andgeom_smooth()when method = "smooth", -
includes a custom
theme_minimal()and title usingrlang::englue().
Test on mpg with both methods to compare relationships between displ and hwy.
Q4: Solution
plot_relationship <- function(df, x, y, method = "point") {
label <- rlang::englue("Relationship: {{x}} vs {{y}}")
base <- ggplot(df, aes(x = {{x}}, y = {{y}})) +
geom_point(alpha = 0.8) +
labs(title = label) +
theme_minimal(base_size = 12)
if (method == "point") {
base
} else if (method == "smooth") {
base + geom_smooth(se = TRUE)
} else {
stop("method must be 'point' or 'smooth'")
}
}
# Examples using mpg
p4_point <- plot_relationship(mpg, displ, hwy, method = "point")
p4_smooth <- plot_relationship(mpg, displ, hwy, method = "smooth")
Method = "point":

Method = "smooth":

Q5. Using mpg, build two scatter plots:
p1- plotdisplon the x-axis andhwyon the y-axisp2- plotctyon the x-axis andhwyon the y-axis
Include the complete theme, theme_minimal(). Stack the plots vertically and horizontally using patchwork.
Q5: Solution
p1 <- ggplot(mpg) +
geom_point(aes(displ, hwy)) + theme_minimal()
p2 <- ggplot(mpg) +
geom_point(aes(cty, hwy)) + theme_minimal()
#vertically
p1 / p2
#horizontally
p1 | p2
Vertical:

Horizontal:

Q6. With the built-in data set economics, make 3 line plots using geom_line() and theme_minimal():
p1- plotdateon the x-axis andunemployon the y-axis. Include a plot title (title = "Unemployment").p2- plotdateon the x-axis andpsaverton the y-axis. Include a plot title (title = "Personal Saving Rate").p3- plotdateon the x-axis andpopon the y-axis. Include a plot title (title = "Population").
Arrange the plots using patchwork. p1 should be on the top (row 1), and p2 and p3 should be oriented horizontally on the bottom (row 2).
Q6: Solution
p1 <- ggplot(economics) +
geom_line(aes(date, unemploy)) + labs(title = "Unemployment") + theme_minimal()
p2 <- ggplot(economics) +
geom_line(aes(date, psavert)) + labs(title = "Personal Saving Rate") + theme_minimal()
p3 <- ggplot(economics) +
geom_line(aes(date, pop)) + labs(title = "Population") + theme_minimal()
(p1 / (p2 | p3))

Q7. Using mtcars, create two plots:
a- a scatter plot withhpon the x-axis andmpgon the y-axisb- a smooth plot withhpon the x-axis andmpgon the y-axis.
Combine the plots in a horizontal orientation (1 row, 2 columns) using patchwork. Use plot_annotation() to include a shared title.
Q7: Solution
a <- ggplot(mtcars) +
geom_point(aes(hp, mpg)) + theme_minimal()
b <- ggplot(mtcars) +
geom_smooth(aes(hp, mpg),se = TRUE) + theme_minimal()
(a | b) + plot_annotation(title = "MPG vs HP: Two Views")

Q8. Write a function, compare_two_vars(df, x, y, group) that makes two plots combined with patchwork.
p1- create a scatter plot taking two arguments,xandy, and color set togroup,p2makes a boxplot ofybygroup, - combines them side-by-side with patchwork.
Test on iris with Sepal.Width (x), Petal.Width (y), grouped by Species.
Q8: Solution
compare_two_vars <- function(df, x, y, group) {
p1 <- ggplot(df) +
geom_point(aes(x = {{x}}, y = {{y}}, color = {{group}})) +
theme_minimal() +
theme(legend.position = "none")
p2 <- ggplot(df) +
geom_boxplot(aes(x = {{group}}, y = {{y}}, fill = {{group}})) +
theme_minimal()
p1 | p2
}
compare_two_vars(iris, Sepal.Width, Petal.Width, Species)
