I'm trying to get the equation for predicted data from a logit model, graphed over the real data.
Using stat_poly_eq (from ggpmisc) works, until I ask it to show the equation.
Here is my function:
plot_logit_lab = function(log_mod){
mod_frame = model.frame(log_mod)
var_names = names(mod_frame)
newdat = setNames(data.frame(seq(min(mod_frame[[2]]), max(mod_frame[[2]]),
len=100)),
var_names[2])
newdat[var_names[1]] = predict(log_mod, newdata = newdat, type="response")
the_plot <- ggplot() +
geom_point(data=mod_frame, aes(x=mod_frame[[2]],
y=mod_frame[[1]])) +
stat_poly_line(data=newdat, mapping=aes(x=newdat[[1]],
y=newdat[[2]])) +
stat_poly_eq(data=newdat, mapping=aes(x=newdat[[1]],
y=newdat[[2]]),
use_label(labels=c("eq")))
return(the_plot)
}
And the error I get trying to run it:
> Error in `check_subclass()`: ! `x` must be either a string or a <Geom> object, not a <uneval> object. > Backtrace: > 1. global plot_logit_lab(car_logit) > 2. ggpmisc::stat_poly_eq(...) > 3. ggplot2::layer(...) > 4. ggplot2:::check_subclass(x = geom)
Without the use_label argument, it works fine (showing an R2 value of 1 because of the predicted values) but the equation is what I'm interested in.
Also, here is my test data and how I'm using the function:
car <- cars %>%
mutate(d = case_when(dist < 50 ~ "less",
dist >= 50 ~ "more"),
s = speed)
car$d <- factor(car$d, levels=c("less","more"))
car_sum <- car %>%
count(s, d) %>%
group_by(s) %>%
mutate(s_n = sum(n),
d_prob = n/sum(n))
car_logit <- glm(formula = d_prob ~ s,
weight = s_n,
family = binomial(link = "logit"),
data = car_sum)
car_plot <- plot_logit_lab(car_logit)
car_plot
The data_logit_no_out function is basically the same as the car_sum step above.

I am not sure if you can use
data = ...anduse_labelwithinstat_poly_eqat the same time (could be a bug, or something that I am missing at the moment). But in any case, if we shuffle things around, define thedatawithinggplot()and add the points usinggeom_pointwith another dataframe at the end, we can get the desired result.Created on 2024-02-19 with reprex v2.0.2