求助:R-Studio中OLS多元回归模型系数对比图绘制问题
Hey there! Let's get that side-by-side coefficient comparison plot working for you. The core issue here is that ggplot thrives on tidy (long-form) data, and it sounds like your combined model results might be in a wide format that doesn't let ggplot distinguish between the two models. Here's a step-by-step fix:
Step 1: Tidy Your Model Results
First, use the broom package to extract coefficients from each model separately, add a label for each model, then combine them into one tidy data frame. This makes it easy for ggplot to group and color by model.
# Load required packages library(broom) library(dplyr) library(ggplot2) # Assume your two OLS models are named model1 and model2 (replace with your actual model names) tidy_model1 <- tidy(model1) %>% mutate(model = "Model 1") # Add model identifier tidy_model2 <- tidy(model2) %>% mutate(model = "Model 2") # Combine the tidy results into one data frame combined_tidy <- bind_rows(tidy_model1, tidy_model2)
Step 2: Plot with ggplot (Color-Coded & Side-by-Side)
Now use the tidy data frame to build your plot. We'll use color = model to distinguish the two models, and position_dodge() to keep their coefficients side by side instead of overlapping.
ggplot(combined_tidy, aes(x = term, y = estimate, color = model, group = model)) + # Add coefficient points, dodged to avoid overlap geom_point(position = position_dodge(width = 0.5), size = 2) + # Add 95% confidence intervals (adjust multiplier if you want different CI) geom_errorbar(aes(ymin = estimate - 1.96 * std.error, ymax = estimate + 1.96 * std.error), width = 0.2, position = position_dodge(width = 0.5)) + # Customize labels and theme labs(title = "OLS Coefficient Comparison: Model 1 vs Model 2", x = "Predictor Variables", y = "Coefficient Estimate", color = "Model") + theme_minimal() + theme(axis.text.x = element_text(angle = 45, hjust = 1)) # Rotate x-labels for readability
If You Already Have a Wide-Format Combined Data Frame
If you've already merged your models into a wide format (e.g., columns like estimate_model1, estimate_model2, std.error_model1), convert it to long-form first with tidyr::pivot_longer():
library(tidyr) # Convert wide to long format combined_long <- your_wide_data %>% pivot_longer( cols = starts_with("estimate"), names_to = "model", values_to = "estimate", names_prefix = "estimate_" # Remove the prefix from model names ) %>% pivot_longer( cols = starts_with("std.error"), names_to = "model_error", values_to = "std.error", names_prefix = "std.error_" ) %>% filter(model == model_error) %>% # Match each model to its standard error select(-model_error)
Then use combined_long in the ggplot code above instead of combined_tidy.
This should give you a clear, color-coded plot where you can easily compare coefficients across both models. Let me know if you need to tweak anything for your specific dataset!
内容的提问来源于stack exchange,提问作者Christina Cranwill

