From data to plot in one pipeline in R
The tidyverse habit: reshape, then plot, without an intermediate variable.
library(dplyr)
library(tidyr)
library(ggplot2)
wide <- tibble(
lang = c("r", "python", "sql"),
week_1 = c(88, 99, 70),
week_2 = c(92, 104, 74),
week_3 = c(96, 101, 79)
)
plot <- wide |>
pivot_longer(starts_with("week"), names_to = "week", values_to = "tpm",
names_prefix = "week_", names_transform = list(
week = as.integer)) |>
mutate(improvement = tpm - first(tpm), .by = lang) |>
ggplot(aes(week, tpm, colour = lang)) +
geom_line(linewidth = 1) +
geom_point(size = 2) +
scale_x_continuous(breaks = 1:3) +
labs(title = "Three weeks", y = "tpm", x = "week") +
theme_minimal()
print(nrow(plot$data))
ggsave(tempfile(fileext = ".png"), plot, width = 5, height = 3, dpi = 100)
How it works
- The pipe carries the data into
ggplot. +continues the plot;|>continues the data.- One expression, so nothing half-built escapes.
Keywords and builtins used here
aescfirstgeom_linegeom_pointggplotggsavelabslibrarylistmutatenrowpivot_longerprintscale_x_continuousstarts_withtempfiletheme_minimaltibble
The run, in numbers
- Lines
- 25
- Characters to type
- 677
- Tokens
- 207
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 118 seconds.
Step 3 of 3 in Finishing a plot, step 14 of 15 in ggplot2.