This post
explains how to build and customize a bump plot with R.
It uses the ggbump package, provides
reproducible code and explain how input data must be
formatted.
For an introduction to bump plots, see this introduction.
The ggbump package provides a
geom_bump()
function that allows to build ggbump
charts.
Install the package with install.packages("ggbump")
.
The input dataset is simple: we just have 3 groups, with one value per group and per year. Here is how to build it:
# Library
#install.packages("ggbump")
library(ggbump)
library(tidyverse)
# Create data
year <- rep(2019:2021, 3)
products_sold <- c(
500, 600, 700,
550, 650, 600,
600, 400, 500
)
store <- c(
"Store A", "Store A", "Store A",
"Store B", "Store B", "Store B",
"Store C", "Store C", "Store C"
)
# Create the new dataframe
df <- data.frame(
year = year,
products_sold = products_sold,
store = store
)
It is possible to add individual points to the bump
chart. This is done by adding a geom_point()
layer.
The geom_text()
and labs()
functions can be
used to add labels and a title to the chart.
ggplot(df, aes(x = year, y = products_sold, color = store)) +
geom_bump(size = 2) +
geom_point(size = 6) +
geom_text(aes(label = store), nudge_y = 20, fontface = "bold", size=3) +
scale_color_brewer(palette = "Paired") +
theme_minimal() +
labs(
title = "Products sold per store",
x = "Year",
y = "Products sold"
)
You might be interested in
👋 After crafting hundreds of R charts over 12 years, I've distilled my top 10 tips and tricks. Receive them via email! One insight per day for the next 10 days! 🔥