Home > Mobile >  Extracting values from ggplot confidence interval
Extracting values from ggplot confidence interval

Time:04-18

I was able to plot a line according to my data using the geom_smooth with method = "lm" in R. However, I was wondering how to extract the values easily from my ggplot. I am particularly interested in the values used to create the confidence interval. Reproducible code is below. Thanks!

app <- structure(list(Year = 2019:2014, NP_total = c(892L, 867L, 765L, 
635L, 572L, 554L)), row.names = c(NA, -6L), class = c("data.table", 
"data.frame"))

ggplot()   geom_smooth(data = app, mapping = aes(x = Year, y = NP_total), color = "black", method = "lm")


CodePudding user response:

Since you are using the "lm" method in geom_smooth, you can use the same method outside of ggplot:

lm(NP_total~Year,app)

To extract the confidence interval, you can use the same "lm" model to predict your NP_total values using the same Year values used to make the model. Here is a one-liner.

smooth_values <- predict(lm(NP_total~Year,app), data = app$Year, se.fit = TRUE)

Make sure to have se.fit = TRUE in the predict function to output the confidence interval you are looking for. I hope this is what you're looking for.

  • Related