2

Trying to reproduce below base code using ggplot which is yielding incorrect result

base code

model1 <- lm(wgt ~ 1, data = bdims)
model1_null <- augment(model1)
plot(bdims$hgt, bdims$wgt)
abline(model1, lwd = 2, col = "blue")
pre_null <- predict(model1)
segments(bdims$hgt, bdims$wgt, bdims$hgt, pre_null, col = "red")

ggplot code

bdims %>% 
  ggplot(aes(hgt, wgt)) +
  geom_point() +
  geom_smooth(method = "lm", formula = bdims$hgt ~ 1) +
  segments(bdims$hgt, bdims$wgt, bdims$hgt, pre_null, col = "red")
0

1 Answer 1

1

Here's an example using the built-in mtcars data:

ggplot(mtcars, aes(wt, mpg)) +
    geom_point() +
    geom_smooth(method = "lm", formula = y ~ 1) + 
    geom_segment(aes(xend = wt, yend = mean(mpg)), col = "firebrick2")

The formula references the aesthetic dimensions, not the variable names. And you need to use geom_segment not the base graphics segments. In a more complicated case you would pre-compute the model's predicted values for the segments, but for a null model it's easy enough to just use mean inline.

enter image description here

Sign up to request clarification or add additional context in comments.

4 Comments

> based on your answer tried by calculating model's predicted value with single variable hgt. here is the sample code 'pre_hgt <- predict(model2) bdims %>% ggplot(aes(hgt, wgt)) + geom_point() + geom_smooth(method = "lm", se = 0) + geom_segment(aes(xend = hgt, yend = pre_hgt), col = "firebrick2")'
I'm not sure what the point of your comment is. I can't run your sample code since you haven't shared any sample data. Are you trying to say "Thanks, this worked great!" or "I can't get this to work on my data."? Either way, I would recommend only using length-1 constants or columns of your data frame inside aes. Using a vector with length > 1 that is not in your data frame like pre_hgt is asking for trouble. Reduce it to a single value or add it to your data frame.
Im new to this place tried commenting more than 3 times and it got locked. I meant to say thanks and included the code which did not include data source which worked after your input 'model2 <- lm(wgt ~ hgt, data = bdims) pre_hgt <- predict(model2) bdims %>% ggplot(aes(hgt, wgt)) + geom_point() + geom_smooth(method = "lm", se = 0) + geom_segment(aes(xend = hgt, yend = pre_hgt), col = "firebrick2")' and point noted in terms of length of constants or columns
Great! If you're not hoping for additional answers, you should "accept" my answer to mark your question as solved. You can do this by clicking the check mark in the left margin next to the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.