基于ggplot2在同图绘制Bland-Altman图及多变量平滑曲线
Hey there! It sounds like you’ve nailed the two scatter groups in your Bland-Altman plot, but hitting a snag when adding smooth curves for your pre.moy/post.moy (x-axis) and pre.dif/post.dif (y-axis) pairs. The most common culprit here is working with wide-format data instead of long-format, which confuses ggplot’s variable mapping for the curves. Let’s walk through a solution step by step.
Step 1: Reshape Your Data to Long Format
First, we need to tidy your data so that the pre/post groups are stored in a single column, and their corresponding mean (moy) and difference (dif) values live in consistent columns. We’ll use tidyr::pivot_longer for this:
library(tidyverse) # Replace `your_data` with the name of your actual data frame tidy_data <- your_data %>% # Reshape mean values into long format pivot_longer( cols = c(pre.moy, post.moy), names_to = "time_point", values_to = "mean_value", names_pattern = "(pre|post)\\.moy" # Extract pre/post from column names ) %>% # Reshape difference values into long format pivot_longer( cols = c(pre.dif, post.dif), names_to = "time_point_dif", values_to = "difference", names_pattern = "(pre|post)\\.dif" ) %>% # Ensure pre/post pairs are matched correctly filter(time_point == time_point_dif) %>% select(-time_point_dif) # Remove redundant column
This gives you a clean long-format data frame where each row represents one observation, with a time_point column to distinguish pre vs post, mean_value for your x-axis, and difference for your y-axis.
Step 2: Plot with Scatter Points + Smooth Curves
Now you can use this tidy data to build your plot. ggplot will automatically handle grouping the scatter points and smooth curves by the time_point variable:
ggplot(tidy_data, aes(x = mean_value, y = difference, color = time_point)) + # Add scatter points with slight transparency to avoid overcrowding geom_point(alpha = 0.6) + # Add smooth loess curves (adjust method to "lm" if you want linear fits) geom_smooth(method = "loess", se = FALSE, linewidth = 1) + # Customize labels and theme labs( x = "Mean of Measurements", y = "Difference Between Measurements", color = "Time Point", title = "Bland-Altman Plot with Grouped Smooth Curves" ) + theme_minimal()
Why This Works
By using long-format data, you’re letting ggplot handle the grouping logic instead of manually trying to map separate pre/post variables across layers. This avoids the "variable splicing" errors you were seeing, because all relevant data is mapped consistently in a single aes() call.
Troubleshooting Tips
- If you still get errors, double-check that your original
pre.moy/post.moyandpre.dif/post.difcolumns have the same number of rows (no missing values that might break the pairing). - If you prefer linear smooth curves instead of loess, change
method = "loess"tomethod = "lm"ingeom_smooth().
内容的提问来源于stack exchange,提问作者PHNM

