Rainclouds with ggrain
A raincloud plot shows a distribution, a box plot, and the observations that produced them. In R, ggrain::geom_rain() adds those layers to a ggplot. The same function can connect repeated measurements by participant ID.
This lesson builds a penguin body mass figure and a second figure with simulated paired measurements. It covers density width, point placement, missing values, and participant identity. The R and Python raincloud comparison shows why two matching box plots can conceal different distributions.
Set up the R session
Section titled “Set up the R session”Use R with ggplot2, ggrain, palmerpenguins, and svglite installed. This example uses ggrain 0.1.2, ggplot2 4.0.3, palmerpenguins 0.1.1, and svglite 2.2.2. Run the blocks in order, or download the complete R script. The script writes its files into an outputs directory under the current working directory.
library(ggplot2)library(ggrain)library(palmerpenguins)
dir.create("outputs", showWarnings = FALSE)options(width = 80)
for (package in c("ggplot2", "ggrain", "palmerpenguins", "svglite")) { cat(package, as.character(packageVersion(package)), "\n")}ggplot2 4.0.3ggrain 0.1.2palmerpenguins 0.1.1svglite 2.2.2Prepare the penguin measurements
Section titled “Prepare the penguin measurements”The penguins table contains measurements collected by Kristen Gorman and the Palmer Station Long Term Ecological Research Program. It includes Adelie, Chinstrap, and Gentoo penguins from the Palmer Archipelago. The dataset documentation describes the observations and their CC0 license.
Keep the species and body mass columns. Remove rows only when one of those values is missing. A missing value in another measurement should not remove a penguin from this figure.
penguin_mass <- as.data.frame(penguins[c("species", "body_mass_g")])keep <- complete.cases(penguin_mass)cat("Rows without species or body mass:", sum(!keep), "\n")penguin_mass <- penguin_mass[keep, ]penguin_mass$species <- droplevels(penguin_mass$species)
species_counts <- table(penguin_mass$species)print(species_counts)species_labels <- paste0( names(species_counts), "\nn = ", as.integer(species_counts))names(species_labels) <- names(species_counts)write.csv(penguin_mass, "outputs/penguin_mass.csv", row.names = FALSE)Rows without species or body mass: 2
Adelie Chinstrap Gentoo 151 68 123Draw the basic raincloud
Section titled “Draw the basic raincloud”Map the category to x, the measurement to y, and the category to fill. Each dot is one recorded body mass. The box contains the middle half of the observations, and its line marks the median. Whiskers reach the most extreme observations within 1.5 interquartile ranges of the box hinges.
The half violin estimates a continuous density. Its width describes relative concentration at a body mass, not the number of penguins. The axis labels report the group sizes separately.
species_colors <- c( Adelie = "#0072B2", Chinstrap = "#D55E00", Gentoo = "#009E73")
penguin_plot <- ggplot( penguin_mass, aes(x = species, y = body_mass_g, fill = species)) + geom_rain( seed = 42, point.args = list(size = 1.2, alpha = 0.45, colour = "grey25"), boxplot.args = list(outlier.shape = NA, alpha = 0.85), violin.args = list( alpha = 0.55, colour = NA, trim = TRUE, scale = "area", adjust = 1 ) ) + scale_fill_manual(values = species_colors) + scale_x_discrete(labels = species_labels) + labs( title = "Penguin body mass by species", subtitle = "Each point is one penguin; clouds show estimated densities.", x = NULL, y = "Body mass (g)", caption = "Data come from palmerpenguins; missing body masses are omitted." ) + theme_classic(base_size = 12) + theme( legend.position = "none", plot.title.position = "plot", plot.caption = element_text(hjust = 0, colour = "grey35") )
ggsave( "outputs/ggrain_penguins.png", penguin_plot, width = 7.2, height = 4.8, units = "in", dpi = 300, bg = "white")
Gentoo measurements lie mostly above the other two species in this sample, while Adelie and Chinstrap measurements overlap. These species distributions combine sexes and years. Island also varies across the dataset. A bump in a density does not identify a biological subgroup. Use those recorded variables for a separate stratified analysis before assigning a cause to the shape.
Control the layers
Section titled “Control the layers”geom_rain() accepts a separate list for each layer. When you supply a list, it replaces that list’s defaults. The example therefore retains outlier.shape = NA in boxplot.args. All observations already appear as points; separate box plot outlier symbols would draw some observations twice.
| Control | Effect |
|---|---|
point.args |
Set point size, opacity, and color. |
boxplot.args |
Set box appearance and suppress duplicate outlier symbols. |
violin.args |
Set density appearance, bandwidth adjustment, and scaling. |
rain.side |
Place clouds on the right, left, or opposite sides of two visits. |
seed |
Reproduce the horizontal jitter of points and connecting lines. |
id.long.var |
Name the column that identifies repeated observations. |
The default point jitter moves observations horizontally and preserves their measured values. Keep vertical jitter at zero for a continuous outcome. adjust = 1 uses the default density bandwidth multiplier; smaller values produce more local peaks, and larger values smooth them away. Inspect the points before interpreting a peak. With scale = "area", cloud width does not encode sample size. trim = TRUE stops each density at its observed range.
For a horizontal figure, add coord_flip() to the finished plot. Keep the categorical variable mapped to x and the measurement mapped to y, as the ggrain documentation requires.
Create paired measurements
Section titled “Create paired measurements”The next dataset is simulated. It represents the same participants measured at baseline and follow up, with a continuous assay response in arbitrary units. It does not describe an intervention or a clinical result.
Create both visits from a shared participant value, then add an individual change at follow up. Keep one row per participant and visit. The fixed seed reproduces this example, while the participant ID records which observations belong together.
set.seed(20261116)participant_count <- 24Lbaseline <- round(rnorm(participant_count, mean = 50, sd = 8), 1)follow_up <- round(baseline + rnorm(participant_count, mean = 4, sd = 5), 1)
paired_data <- data.frame( participant_id = rep(sprintf("P%02d", seq_len(participant_count)), each = 2), visit = factor( rep(c("Baseline", "Follow up"), times = participant_count), levels = c("Baseline", "Follow up") ), response = as.vector(rbind(baseline, follow_up)))print(head(paired_data)) participant_id visit response1 P01 Baseline 32.92 P01 Follow up 36.83 P02 Baseline 46.94 P02 Follow up 55.15 P03 Baseline 49.86 P03 Follow up 60.9Check the participant IDs
Section titled “Check the participant IDs”An ID must identify the same participant at both visits. Duplicate participant and visit rows can create misleading line segments. Missing visits change the population represented by each cloud. This example requires complete pairs and stops when either problem occurs.
#' Validate complete pairs for a two-visit raincloud plot.#'#' @param data A data frame with participant_id, visit, and response columns.#' @return The input data, sorted by participant and visit.#' @exportValidatePairs <- function(data) { required <- c("participant_id", "visit", "response") if (!all(required %in% names(data)) || nrow(data) == 0L) { stop("Supply nonempty data with participant_id, visit, and response.") } visits <- c("Baseline", "Follow up") if (anyNA(data[required]) || any(trimws(data$participant_id) == "")) { stop("Participant IDs, visits, and responses must be present.") } if (!is.numeric(data$response) || any(!is.finite(data$response))) { stop("Responses must be finite numbers.") } if (!all(data$visit %in% visits)) { stop("Visit must be Baseline or Follow up.") } if (anyDuplicated(data[c("participant_id", "visit")]) > 0L) { stop("Each participant must have only one row per visit.") } data$visit <- factor(data$visit, levels = visits) counts <- table(data$participant_id, data$visit) if (any(counts != 1L)) { stop("Each participant must have both visits.") } data[order(data$participant_id, data$visit), ]}
paired_data <- ValidatePairs(paired_data)cat("Complete participants:", length(unique(paired_data$participant_id)), "\n")cat("Observations:", nrow(paired_data), "\n")write.csv(paired_data, "outputs/paired_measurements.csv", row.names = FALSE)Complete participants: 24Observations: 48For an actual study, report incomplete pairs and decide how the analysis handles them before drawing the figure. Do not silently remove a visit to make the lines convenient. If technical replicates exist, define the participant level measurement before this check.
Connect the correct observations
Section titled “Connect the correct observations”Pass the ID column name as a string to id.long.var. Keep the global fill mapped to visit. A global group = participant_id would also split the density and box plot layers by participant, which is not the intended summary.
rain.side = "f1x1" puts the two clouds outside the pair of visits. Gray lines connect the measurements in the center. The default point and line positions share the same jitter seed, so each line reaches its corresponding points.
With ggplot2 4.0.3, this ggrain 0.1.2 layout emits a warning about the deprecated size aesthetic in its polygon code. The plot still renders. The warning concerns the cloud outline, not the participant IDs or measured values.
visit_counts <- table(paired_data$visit)visit_labels <- paste0( names(visit_counts), "\nn = ", as.integer(visit_counts))names(visit_labels) <- names(visit_counts)
paired_plot <- ggplot( paired_data, aes(x = visit, y = response, fill = visit)) + geom_rain( id.long.var = "participant_id", rain.side = "f1x1", seed = 42, point.args = list(size = 1.8, alpha = 0.85, colour = "grey20"), line.args = list(alpha = 0.35, linewidth = 0.4, colour = "grey40"), boxplot.args = list(outlier.shape = NA, alpha = 0.85), violin.args = list( alpha = 0.55, colour = NA, trim = TRUE, scale = "area", adjust = 1 ) ) + scale_fill_manual(values = c(Baseline = "#0072B2", "Follow up" = "#D55E00")) + scale_x_discrete(labels = visit_labels, expand = expansion(add = 0.65)) + labs( title = "Paired assay measurements", subtitle = "Simulated data; each line connects the same participant.", x = NULL, y = "Assay response (arbitrary units)", caption = "Clouds summarize visits; lines show individual changes." ) + theme_classic(base_size = 12) + theme( legend.position = "none", plot.title.position = "plot", plot.caption = element_text(hjust = 0, colour = "grey35") )
ggsave( "outputs/ggrain_paired.png", paired_plot, width = 7.2, height = 4.8, units = "in", dpi = 300, bg = "white")
The clouds summarize each visit separately. The lines expose the direction and variation of the individual changes. Cloud overlap does not test a paired mean change. For inference, use the study design and a method that retains the pairing, such as those in the paired tests lesson.
Export the figures
Section titled “Export the figures”The PNG files use a white background and 300 dots per inch at the specified physical size. For a journal that accepts vector artwork, save SVG copies. Text and lines remain vector elements when the figure is resized. Inspect the labels at the intended print size, and retain the source script with the input data.
ggsave( "outputs/ggrain_penguins.svg", penguin_plot, device = svglite::svglite, width = 7.2, height = 4.8, units = "in", bg = "white")ggsave( "outputs/ggrain_paired.svg", paired_plot, device = svglite::svglite, width = 7.2, height = 4.8, units = "in", bg = "white")print(sort(list.files("outputs", pattern = "\\.(png|svg|csv)$")))[1] "ggrain_paired.png" "ggrain_paired.svg"[3] "ggrain_penguins.png" "ggrain_penguins.svg"[5] "paired_measurements.csv" "penguin_mass.csv"Download the penguin SVG, the paired SVG, the penguin table, or the simulated paired table to inspect these examples outside the page.
Scientific references
Section titled “Scientific references”Allen and colleagues, 2021 describe raincloud plots, which combine a density, a box plot, and the raw data points.
Horst, Hill, and Gorman, 2020 publish the Palmer Archipelago penguin data in the palmerpenguins package.
Further reading
Section titled “Further reading”The ggrain vignette explains layer placement, covariate colors, and layouts with additional groups and visits. Use it when the two visit layout no longer matches your design.
The palmerpenguins introduction describes the measured variables and original data sources. It helps you decide which strata to retain when adapting the body mass figure.
The ggplot2 export documentation explains file formats, dimensions, and resolution. Use it to match a journal’s artwork requirements.