在R中绘制仅含线条与误差带的性别分组增长曲线模型
Got it, let's get that clean growth curve plot sorted for you! Since you already have your lmer model set up, we'll focus on generating predicted values with confidence intervals and then visualizing them with lines and error bands, split by male/female. Here's how to do it step by step:
Step 1: Load required packages
First, make sure you have these packages installed (if not, use install.packages() to grab them):
library(lme4) library(ggplot2) library(emmeans) # Makes calculating predicted means + CIs for mixed models straightforward
Step 2: Generate prediction data
To plot smooth curves, we need a dataset that covers the full range of your age variable, paired with both levels of FEMALE (0 = male, 1 = female) and a representative value for SES (we'll use the mean here, but you can adjust this to show low/mid/high SES if needed):
# Create a sequence of age values spanning your data's range age_range <- seq(min(df1$age, na.rm = TRUE), max(df1$age, na.rm = TRUE), length.out = 100) # Build a grid of predictor values for predictions pred_grid <- expand.grid( age = age_range, SES = mean(df1$SES, na.rm = TRUE), # Use mean SES for average-case predictions FEMALE = c(0, 1) # Both male and female )
Step 3: Get predicted means and confidence intervals
We'll use emmeans() to extract marginal predicted values (averaged over random effects) and their 95% confidence intervals from your model:
# Calculate predicted means across age and gender model_means <- emmeans(m, ~ age * FEMALE, at = list(age = age_range, SES = mean(df1$SES, na.rm = TRUE))) # Convert to a data frame for plotting plot_data <- as.data.frame(model_means) # Rename the FEMALE variable to something more readable for the plot plot_data$gender <- factor(plot_data$FEMALE, levels = c(0, 1), labels = c("MALE", "FEMALE"))
Step 4: Plot with ggplot2
Now we'll build the plot with lines for each gender and shaded error bands, no raw data points:
ggplot(plot_data, aes(x = age, y = emmean)) + # Add shaded error bands (alpha controls transparency) geom_ribbon(aes(ymin = lower.CL, ymax = upper.CL, fill = gender), alpha = 0.2, color = NA) + # Add the growth curves geom_line(aes(color = gender), linewidth = 1) + # Customize labels and theme labs( x = "Age", y = "Predicted Height", color = "Gender", fill = "Gender" ) + theme_minimal() + # Clean up the plot (remove minor grid lines if desired) theme(panel.grid.minor = element_blank())
Quick notes:
- If you want to show curves for different SES levels (e.g., low, medium, high), just add those values to the
SESargument inexpand.grid()and adjust the plot to color/group by both gender and SES (e.g.,aes(color = interaction(gender, SES))). - If you prefer conditional predictions (including individual random effects for each ID), you can use
predict(m, newdata = pred_grid, re.form = NULL)instead ofemmeans(), but you'll need to calculate confidence intervals manually (bootstrapping is a common method here).
内容的提问来源于stack exchange,提问作者Oscar

