UC San Diego
COGS 137 - Fall 2026
2026-10-12
ggplot2Q: Why use factors? And are factors basically ordered dictionaries? what is the benefit
A: I can see the thought of dictionaries, but they don’t have key value pairs. They have values where there is a meaningful order. I introduced it as helpful for plotting (which is true) but it’s also helpful in modeling, when you have reference group to compare against - having this as the first level is then meaningful. We’ll see this in a few weeks!
Q: When should you factor variables?
A: You should factor when there is a natural/meaningful order to the values in the categorical variable. For occasional/frequent, the order matters there for which you think of as “first” - I think occassional would want to be plotted before frequent, so ordering the variable as such makes sense.
Q: I want to pull a percentage of a group. Ie. the top 25% of THC values. not sure how to do this…
Due Dates:
Notes:
Rows: 1,525
Columns: 14
$ ID <chr> "11255", "11255", "11255", "11255", "11255", "11255", …
$ Treatment <chr> "5.90%", "5.90%", "5.90%", "5.90%", "5.90%", "5.90%", …
$ Group <chr> "Occasional user", "Occasional user", "Occasional user…
$ `FLUID TYPE` <chr> "WB", "WB", "WB", "WB", "WB", "WB", "WB", "WB", "WB", …
$ Timepoint <chr> "T1", "T2A", "T2B", "T3A", "T3B", "T4A", "T4B", "T5A",…
$ CBN <dbl> 0.0, 2.8, 0.6, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 4.6,…
$ CBD <dbl> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, …
$ THC <dbl> 0.5, 32.4, 5.1, 3.2, 1.8, 1.2, 0.9, 0.8, 0.6, 0.0, 46.…
$ `11-OH-THC` <dbl> 0.0, 5.4, 2.4, 1.8, 1.4, 0.0, 0.0, 0.0, 0.0, 0.0, 7.7,…
$ `THC-COOH` <dbl> 5.7, 13.5, 11.7, 9.7, 8.7, 6.7, 6.8, 6.8, 6.3, 1.9, 13…
$ `THC-COOH-Gluc` <dbl> 4.9, 4.4, 6.2, 8.4, 8.9, 8.2, 7.5, 7.1, 6.1, 2.1, 2.7,…
$ CBG <dbl> 0.0, 1.2, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 2.0,…
$ `THC-V` <dbl> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, …
$ time.from.start <dbl> -27, 15, 69, 111, 156, 236, 283, 315, 360, -10, 20, 73…
We’ve packaged the cleaning from the dplyr notes into one function, clean_cs01(), saved in src/cs01_functions.R (along with additional fucntions that will be helpful for cs01):
# ==== Time windows ============================================================
# Windows (minutes from start of smoking) differ by matrix, following the paper.
# `cut()` intervals are right-closed: (0, 30] is "0-30 min"; anything <= 0 is
# pre-smoking; the last window is open-ended.
cs01_windows <- list(
WB = list(breaks = c(-Inf, 0, 30, 70, 100, 180, 210, 240, 270, 300, Inf),
labels = c("pre-smoking", "0-30 min", "31-70 min", "71-100 min",
"101-180 min", "181-210 min", "211-240 min",
"241-270 min", "271-300 min", "301+ min")),
OF = list(breaks = c(-Inf, 0, 30, 90, 180, 210, 240, 270, Inf),
labels = c("pre-smoking", "0-30 min", "31-90 min", "91-180 min",
"181-210 min", "211-240 min", "241-270 min", "271+ min")),
BR = list(breaks = c(-Inf, 0, 40, 90, 180, 210, 240, 270, Inf),
labels = c("pre-smoking", "0-40 min", "41-90 min", "91-180 min",
"181-210 min", "211-240 min", "241-270 min", "271+ min"))
)
# The first window after smoking, for each matrix
cs01_early_windows <- c("0-30 min", "0-40 min")
# Compounds measured (not every matrix has every compound)
cs01_compounds <- c("cbn", "cbd", "thc", "thcoh", "thccooh", "thccooh_gluc",
"cbg", "thcv", "thca_a")# ==== Cleaning ================================================================
# Clean one raw CS01 file (Blood.csv, OF.csv, or Breath.csv).
# fluid: "WB", "OF", or "BR" (determines the time windows)
clean_cs01 <- function(df, fluid = c("WB", "OF", "BR")) {
fluid <- match.arg(fluid)
win <- cs01_windows[[fluid]]
df |>
janitor::clean_names() |>
rename(any_of(c(fluid_type = "fluid",
thcoh = "x11_oh_thc",
thccooh = "thc_cooh",
thccooh_gluc = "thc_cooh_gluc",
thcv = "thc_v",
thc = "thc_pg_pad"))) |>
mutate(
treatment = fct_recode(treatment,
"5.9% THC (low dose)" = "5.90%",
"13.4% THC (high dose)" = "13.40%"),
treatment = fct_relevel(treatment, "Placebo", "5.9% THC (low dose)"),
group = case_match(group,
"Experienced user" ~ "Frequent user",
"Not experienced user" ~ "Occasional user",
.default = group),
timepoint = cut(time_from_start, breaks = win$breaks, labels = win$labels)
)
} Compare to the case_when() in the dplyr notes: what does cut() do here?
WB |>
filter(timepoint=="0-30 min") |>
ggplot(., mapping = aes(x = thc, y = thccooh,
color = treatment)) +
geom_point() +
labs(title = "THC and THC-COOH levels (0-30 min)",
subtitle = "THC levels remain low in placebo group; THC-COOH is variable",
x = "THC (ng/mL)", y = "THC-COOH (ng/mL)",
color = "Treatment Group") +
scale_color_viridis_d()Start with the
WBdata frame (filtering to only include first timepoint)
Start with the
WBdata frame, map thc levels to the x-axis
Start with the
WBdata frame, map thc levels to the x-axis and map thccooh levels to the y-axis.
Start with the
WBdata frame, map thc levels to the x-axis and map thccooh levels to the y-axis. Represent each observation with a point.
Start with the
WBdata frame, map thc levels to the x-axis and map thccooh levels to the y-axis. Represent each observation with a point and map treatment group to the color of each point.
Start with the
WBdata frame, map thc levels to the x-axis and map thccooh levels to the y-axis. Represent each observation with a point and map treatment group to the color of each point. Title and subtitle the plot.
Start with the
WBdata frame, map thc levels to the x-axis and map thccooh levels to the y-axis. Represent each observation with a point and map treatment group to the color of each point. Title and subtitle the plot, label the x and y axes
Start with the
WBdata frame, map thc levels to the x-axis and map thccooh levels to the y-axis. Represent each observation with a point and map treatment group to the color of each point. Title and subtitle the plot, label the x and y axes, and title the legend.
WB |>
filter(timepoint=="0-30 min") |>
ggplot(., mapping = aes(x = thc, y = thccooh,
color = treatment)) +
geom_point() +
labs(title = "THC and THC-COOH levels (0-30 min)",
subtitle = "THC levels remain low in placebo group; THC-COOH is variable",
x = "THC (ng/mL)", y = "THC-COOH (ng/mL)",
color = "Treatment Group") 
Start with the
WBdata frame, map thc levels to the x-axis and map thccooh levels to the y-axis. Represent each observation with a point and map treatment group to the color of each point. Title and subtitle the plot, label the x and y axes, and title the legend. Finally, use a discrete color scale that is designed to be perceived by viewers with common forms of color blindness.
WB |>
filter(timepoint=="0-30 min") |>
ggplot(., mapping = aes(x = thc, y = thccooh,
color = treatment)) +
geom_point() +
labs(title = "THC and THC-COOH levels (0-30 min)",
subtitle = "THC levels remain low in placebo group; THC-COOH is variable",
x = "THC (ng/mL)", y = "THC-COOH (ng/mL)",
color = "Treatment Group") +
scale_color_viridis_d()
WB |>
filter(timepoint=="0-30 min") |>
ggplot(., mapping = aes(x = thc, y = thccooh,
color = treatment)) +
geom_point() +
labs(title = "THC and THC-COOH levels (0-30 min)",
subtitle = "THC levels remain low in placebo group; THC-COOH is variable",
x = "THC (ng/mL)", y = "THC-COOH (ng/mL)",
color = "Treatment Group") +
scale_color_viridis_d()
Start with the WB data frame, map thc levels to the x-axis and map thccooh levels to the y-axis.
Represent each observation with a point and map treatment group to the color of each point.
Title and subtitle the plot, label the x and y axes, and title the legend.
Finally, use a discrete color scale that is designed to be perceived by viewers with common forms of color blindness.
Tip
You can omit the names of first two arguments when building plots with ggplot().
Generate a basic plot in ggplot2 using different filtering and/or variables than those in the last example (last example: thc & thccoooh, “0-30 min” timepoint).
Commonly used characteristics of plotting characters that can be mapped to a specific variable in the data are
colorshapesizealpha (transparency)aes()geom_*() (this was geom_point() in the previous example, but we’ll learn about other geoms soon!)Edit the basic plot you created earlier to change something about its aesthetics.
geomsgeomsgeom 1 |
Description 2 |
|---|---|
geom_point |
scatterplot |
geom_bar |
barplot |
geom_line |
line plot |
geom_density |
densityplot |
geom_histogram |
histogram |
geom_boxplot |
boxplot |
Generate a plot in ggplot2 using a different geom than what you did previously. Customize as much as you can before time is “up.”
ggplot2?ggplot2 code? Can I create plots using ggplot2?geom is and do I know the basic plots available?These slides aren’t covered in lecture. Use them as a reference. [Time permitting we’ll - in a later lecture - use these with GenAI]
Mapped to a different variable than treatment
Mapped to same variable as color
facet_grid2d grid; `rows ~ cols
facet_wrap“1d ribbon wrapped according to number of rows and columns specified or available plotting area”