UC San Diego
COGS 137 - Fall 2026
2026-10-18
Q: How exactly do color choice and visualization are restricted to certain geom plots?
A: I’m not sure I totally understand the question. But, you can control color on all geoms. The specific parameter may differ, but all color can be controlled.
Q: Is there a guide to different data visualizations and what is best where?
A: Yup! https://www.data-to-viz.com/
Q: I’m curious about how group assignments are divided into groups.
A: I break it into those who typically attend class, those who occassionally attend class, and those who don’t attend class and then randomly assign within those groups. This will be announced this week.
Due Dates:
Note: cs01 groups will (for real this time) be sent out tomorrow
Instructions are on course website.
Note:
See & Discuss: https://cogs137-fa26.github.io/cogs137-fa26/content/cs/cs-example.html
Feedback to other students here
Common comments:
This is NOT the rubric for your case study, but it will be similar:
The process of really getting to “know” your data:
Notes:
Which compound, in which matrix, and at what cutoff is the best biomarker of recent use?
Three matrices:
Variables:
ID | participants identifierTreatment | placebo, 5.90%, 13.40%Group | Occasional user, Frequent userTimepoint | indicator of which point in the timeline participant’s collection occurredtime.from.start | number of minutes from consumptionReading in the csv provided in lab03/cs01:
Defined once in src/cs01_functions.R (and used by clean_cs01(), which made the time windows in this file):
# ==== 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")For a single compound…
But, we have three different matrices…
But what if we consider our experiment/the structure of our data? We have three different matrices…and a whole bunch of compounds. With wide data, it’s not easy to plot these distributions, so you may want to pivot those data….
Distributions across all compounds:
…but this still doesn’t get at the differences between matrices and compound.
We start to get a sense of the data with these quick and dirty plots, but we’re really only scratching the surface of what’s going on in these data.
These data require a lot of exploration due to the number of compounds, multiple matrices, and data over time aspects.
Functions & working across time windows.
Q: When is the due date for case study since I am busy with midterms this two weeks
A: CS01 is due next Sunday, after week 5 (11/01)
Due Dates:
Notes:
You should consider writing a function whenever you’ve copied and pasted a block of code more than twice -Hadley
Shared colors & theme (used by every CS01 plot):
# ==== Plotting ================================================================
cs01_colors <- c("Frequent user" = "#19831C", "Occasional user" = "#A27FC9")
theme_cs01 <- function(base_size = 12) {
theme_classic(base_size = base_size) +
theme(legend.position = "bottom",
legend.title = element_blank(),
panel.grid = element_blank(),
plot.title.position = "plot",
strip.background = element_blank())
}Our first user-defined function takes the data and the matrix as arguments:
# Every measurement over time for one matrix, one panel per compound
plot_scatter_time <- function(df_long, matrix) {
df_long |>
filter(fluid_type == matrix, !is.na(time_from_start), !is.na(value)) |>
ggplot(aes(x = time_from_start, y = value, color = group)) +
geom_point() +
facet_wrap(~compound, scales = "free") +
scale_color_manual(values = cs01_colors) +
labs(title = matrix, x = "Time From Start (min)", y = "Measurement") +
theme_cs01()
}Now to pivot_longer that…
Note
While I drop duplicates after making the plots above, you and your group will want to think about when it should be done for telling the clearest story. The order we do things in EDA is not typically the order in which we communicate information.
One function for both “frequency of use” and “treatment” comparisons: x says what to compare.
# Boxplots at the first post-smoking window for one matrix.
# x: the variable to compare (e.g., group or treatment), unquoted
plot_boxplots <- function(df_long, matrix, x) {
df_long |>
filter(fluid_type == matrix,
timepoint %in% cs01_early_windows,
!is.na(value)) |>
ggplot(aes(x = {{ x }}, y = value, fill = group)) +
geom_boxplot(outlier.shape = NA, alpha = 0.6) +
geom_point(position = position_jitterdodge(jitter.width = 0.2, jitter.height = 0),
size = 0.8, color = "gray40") +
facet_wrap(~compound, scales = "free") +
scale_x_discrete(labels = function(x) str_wrap(x, width = 10)) +
scale_y_continuous(limits = c(0, NA), expand = expansion(mult = c(0, 0.1))) +
scale_fill_manual(values = cs01_colors) +
labs(title = matrix, x = NULL, y = "Measurement (ng/mL)") +
theme_cs01()
}ggplot2 settings live in theme_cs01() and cs01_colors, and one function makes both sets of boxplots. When you find yourself copy-pasting plot code, that’s a function waiting to happen.Sensitivity, specificity & choosing cutoffs: the core of the CS01 question.
Q: on our case study, how much should we be leaving comments to explain the code? I typically leave a comment on every line in the hws/labs just to help me articulate why i did something but i don’t know if this would clutter the cs report we submit as a group. what’s your preference as the grader/person reading it?s
A: Good question! For case studies, we want this to be an effective report. Commenting every line would make teh code less readable, so we’ll want to avoid that. Instead, we’ll want a bit of text before the code to explain at a high-level what was done and then let the code speak for itself. Comments here or there are great!
Due Dates:
Notes:
Sensitivity | the ability of a test to correctly identify patients with a disease/trait/condition. \[TP/(TP + FN)\]
Specificity | the ability of a test to correctly identify people without the disease/trait/condition. \[TN/(TN + FP)\]
❓ For this analysis, do you care more about sensitivity? about specificity? equally about both?
Post-smoking (cutoff > 0)
Pre-smoking
Cannot be a TP or FN before consuming…
Warning
This is beyond code I would expect you all to be able to write yourself. It’s here so that 1) you can make these calculations and interpret the results, 2) because we have a wide range of background and experience. I want everyone to get as much as they can out of this course, and 3) I do want you all to talk to one another. That’s one reason you all are in groups for case studies.
For every matrix × compound × time window × cutoff, count TPs, FNs, FPs, and TNs.
cross_join())group_by() + summarize() to count…exactly what you learned in the dplyr notes# ==== Sensitivity & specificity ===============================================
# For every matrix x compound x time window x cutoff:
# "used" = received THC AND sample taken after smoking
# "detected" = value at or above the cutoff
# Pre-smoking samples count as true negatives/false positives only.
sens_spec <- function(df_long, cutoffs = c(0.5, 1, 2, 5, 10)) {
df_long |>
filter(!is.na(value), !is.na(timepoint)) |>
cross_join(tibble(cutoff = cutoffs)) |>
mutate(used = treatment != "Placebo" & timepoint != "pre-smoking",
detected = value >= cutoff) |>
group_by(fluid_type, compound, timepoint, cutoff) |>
summarize(TP = sum(used & detected),
FN = sum(used & !detected),
FP = sum(!used & detected),
TN = sum(!used & !detected),
.groups = "drop") |>
mutate(N = TP + FN + FP + TN,
sensitivity = TP / (TP + FN),
specificity = TN / (TN + FP),
ppv = TP / (TP + FP),
npv = TN / (TN + FN),
efficiency = (TP + TN) / N)
}Reminder: Currently, states have laws on the books from zero tolerance (detection of any level) to 5ng/mL THC
# A tibble: 720 × 14
fluid_type compound timepoint cutoff TP FN FP TN N
<chr> <chr> <chr> <dbl> <int> <int> <int> <int> <int>
1 BR thc 0-40 min 0.5 124 1 16 47 188
2 BR thc 0-40 min 1 124 1 16 47 188
3 BR thc 0-40 min 2 124 1 16 47 188
4 BR thc 0-40 min 5 124 1 16 47 188
5 BR thc 0-40 min 10 124 1 16 47 188
6 BR thc 181-210 min 0.5 7 51 1 31 90
7 BR thc 181-210 min 1 7 51 1 31 90
8 BR thc 181-210 min 2 7 51 1 31 90
9 BR thc 181-210 min 5 7 51 1 31 90
10 BR thc 181-210 min 10 7 51 1 31 90
# ℹ 710 more rows
# ℹ 5 more variables: sensitivity <dbl>, specificity <dbl>, ppv <dbl>,
# npv <dbl>, efficiency <dbl>
cs01_ss |>
filter(compound == "thc", cutoff == 5) |>
select(fluid_type, timepoint, TP, FN, FP, TN, sensitivity, specificity)# A tibble: 26 × 8
fluid_type timepoint TP FN FP TN sensitivity specificity
<chr> <chr> <int> <int> <int> <int> <dbl> <dbl>
1 BR 0-40 min 124 1 16 47 0.992 0.746
2 BR 181-210 min 7 51 1 31 0.121 0.969
3 BR 211-240 min 12 53 1 33 0.185 0.971
4 BR 241-270 min 4 53 0 26 0.0702 1
5 BR 271+ min 10 53 2 24 0.159 0.923
6 BR 41-90 min 18 30 1 40 0.375 0.976
7 BR 91-180 min 24 64 0 30 0.273 1
8 BR pre-smoking 0 0 6 185 NaN 0.969
9 OF 0-30 min 128 1 3 60 0.992 0.952
10 OF 181-210 min 36 29 0 37 0.554 1
# ℹ 16 more rows
Note: requires library(patchwork)
# Sensitivity (left) & specificity (right) across time windows, one line per cutoff
plot_cutoffs <- function(ss, fluid, cpd, title = fluid) {
df <- ss |>
filter(fluid_type == fluid, compound == cpd) |>
mutate(timepoint = factor(timepoint, levels = cs01_windows[[fluid]]$labels),
cutoff = factor(cutoff))
base <- function(y, ylab) {
ggplot(df |> filter(!is.na({{ y }})),
aes(x = timepoint, y = {{ y }} * 100, color = cutoff, group = cutoff)) +
geom_line(linewidth = 1.2) +
geom_point() +
scale_y_continuous(limits = c(0, 100)) +
scale_x_discrete(drop = FALSE) +
# colorblind-friendly sequential palette (darker = higher cutoff)
scale_color_viridis_d(name = "Cutoff (ng/mL)", end = 0.85, direction = -1) +
labs(x = "Time Window", y = ylab) +
theme_cs01() +
theme(axis.text.x = element_text(angle = 45, hjust = 1))
}
(base(sensitivity, "Sensitivity (%)") + labs(title = paste0(title, ": ", toupper(cpd)))) +
base(specificity, "Specificity (%)") +
patchwork::plot_layout(guides = "collect") &
theme(legend.position = "bottom", legend.title = element_text())
}Our current question asks for a single compound…and you’ll need to decide that.
…but you could imagine a world where more than one compound or more than one matrix could be measured at the roadside.
So:
Things to keep in mind:
Important
Avoid the temptation to assign “Analysis” to one group member. You’ll all likely have to contribute here.