如何在ggplot2中实现逻辑回归绘图?代码修改遇阻求助
Fixing Logistic Regression Plot in ggplot2
Got it, let's get this sorted for you! The problem with your initial attempt is twofold: a tiny typo, and misunderstanding how ggplot handles logistic regression fits. Here's how to replicate your linear regression-style plot with a binary outcome:
Key Fixes & Explanation
- First,
Binominalis misspelled—it should bebinomial(lowercase 'b'). But more importantly, logistic regression is a type of Generalized Linear Model (GLM), so you need to usemethod="glm"and specify the binomial family as an argument to that method, not usemethod="binomial"directly.
Full Code Example
Assuming your dataset is named df, with a continuous predictor (e.g., predictor) and your binary Score1 variable (0/1), here's the code to make a plot matching your original linear regression chart's structure:
library(ggplot2) # Recreate your plot with logistic regression fit ggplot(df, aes(x = predictor, y = Score1)) + # Keep scatter points (add jitter if points overlap heavily) geom_point(alpha = 0.3) + # Logistic regression fit with confidence intervals (matches lm's default se=TRUE) geom_smooth( method = "glm", method.args = list(family = binomial), se = TRUE, color = "#0072B2" # Use your original plot's line color here ) + # Match your original plot's labels and theme labs( x = "Your Predictor Variable Name", y = "Probability of Score1 = 1" ) + theme_bw() # Or use your original theme (e.g., theme_classic())
Extra Tips for Matching Your Original Chart
- If your original linear regression plot used
geom_jitter()instead ofgeom_point()to handle overlapping points, swap that in—binary outcomes often have overlapping 0/1 points, so jitter can help visibility. - Copy over any other elements from your original plot: axis titles, theme settings, annotations, or color scales to keep the layout identical.
- If you need to extract the predicted probabilities manually (for labels or further analysis), you can fit the glm model separately and add predictions to your dataset, but
geom_smooth()handles the plotting automatically.
内容的提问来源于stack exchange,提问作者Evan
相关产品推荐
相关产品推荐

