Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract data from a regression model plot in R?

Tags:

r

this is my code:

library(tidyverse)
if (!require(performance) ) { 
       install.packages("performance");library(performance)} 
if (!require(see) ) {install.packages("see");library(see)} 
# defining a model
model <- lm(mpg ~ wt + am + gear + vs * cyl, data = mtcars)

check_model(model)

How can I obtain the dataframe related to the Normality of Residuals Chart?

enter image description here

I need to replicate this chart and I dont know how to extract the data.

Any help?

like image 406
Laura Avatar asked Oct 25 '25 14:10

Laura


1 Answers

You could dig around in the code of see:::plot.see_check_normality, but it's pretty complicated. The easier/hackier alternative is to use ggplot_build to export the data used in the ggplot object, as below ...

library(performance)
library(ggplot2)
m <- lm(mpg ~ wt + cyl + gear + disp, data = mtcars)
result <- check_normality(m)
p <- plot(result)
print(p)

qq-plot

g <- ggplot_build(p)
d <- g$data[[2]]
plot(d$x, d$y)

same data again

@stefan points out that d <- layer_data(p, i = 2) will retrieve the same information (if you omit the p argument it will take the data from the last ggplot rendered, but I think it's better to be explicit)

like image 93
Ben Bolker Avatar answered Oct 27 '25 02:10

Ben Bolker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!