You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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, Binominal is misspelled—it should be binomial (lowercase 'b'). But more importantly, logistic regression is a type of Generalized Linear Model (GLM), so you need to use method="glm" and specify the binomial family as an argument to that method, not use method="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 of geom_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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:17:06