如何在ggalluvial中为alluvia添加受试者ID标签?
Adding Subject IDs to Alluvia in ggalluvial
Absolutely, you can add subject IDs as labels to the alluvia (the flowing segments) instead of just the stratum boxes. Here's how to adjust your code to make that happen, plus some tips for clean, readable labels:
Modified Code
library(ggalluvial) data(vaccinations) levels(vaccinations$response) <- rev(levels(vaccinations$response)) # Create a subset to avoid duplicate labels (each subject appears in every survey) # We'll place labels at the first survey for clarity label_data <- vaccinations[vaccinations$survey == levels(vaccinations$survey)[1], ] ggplot(vaccinations, aes(x = survey, stratum = response, alluvium = subject, y = freq, fill = response)) + scale_x_discrete(expand = c(.1, .1)) + geom_flow() + geom_stratum(alpha = .5) + # Keep your existing stratum response labels geom_text(stat = "stratum", aes(label = response), size = 3) + # Add subject ID labels to the alluvia geom_text(data = label_data, aes(label = subject), stat = "alluvium", size = 2.5, hjust = 1, color = "darkblue") + theme(legend.position = "none") + ggtitle("Vaccination Survey Responses (with Subject IDs on Alluvia)")
Key Details to Note
- Using
stat = "alluvium": This tells ggplot to anchor the text to the flowing alluvial segments, not the stratum boxes—exactly what you need for labeling the streams. - Avoiding duplicate labels: Since each subject has a row for every survey, we create
label_datato pick just one survey (the first one here) to place each subject's label. This prevents the same ID from appearing multiple times along a single alluvium. - Tweaking label placement: The
hjust = 1parameter shifts labels to the left of the alluvium's start, so they don't overlap with the stratum box. You can adjusthjust,vjust,size, orcolorto fit your plot's needs. - Handling multiple subjects per alluvium: If your data groups 2-5 subjects under one alluvium, you can combine their IDs into a single label using
dplyrto aggregate:library(dplyr) # Group by your alluvium identifier and combine subject IDs combined_label_data <- vaccinations %>% group_by(alluvium) %>% slice(1) %>% # Grab one row per alluvium mutate(combined_subjects = paste(subject, collapse = "\n")) # Then use this in geom_text: aes(label = combined_subjects)
This method gives you full control over how subject IDs are displayed on your alluvial plot, whether you need individual or combined labels.
内容的提问来源于stack exchange,提问作者captcoma
相关产品推荐
相关产品推荐

