Emman
Emman

Reputation: 4201

How to mark the y-values of data points in a given ggplot object?

I'm trying to annotate the y-values of data points in a given ggplot object, after the fact.

To have a reproducible example, I'll create a model on mtcars data, using lm(), and plot using sjPlot::plot_model().

library(magrittr)
library(sjPlot)

given_p_object <- 
  mtcars %>% 
  lm(mpg ~ as.factor(gear), data = .) %>% 
  sjPlot::plot_model(., type = "pred")

So my question starts here: say that I'm given the object given_p_object. I execute it and get the plot:

> given_p_object

given_plot

Is it possible to mark the y-values for each point on the plot, without referring back to the original data and the process that led to the plot (thus ignoring mtcars %>% lm() %>% sjPlot::plot_model())? In other words, how can I extract from within the current given_p_object the information needed to do the following? demo

Upvotes: 1

Views: 127

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388797

Those values can be found in :

given_p_object$gear$data$predicted
#[1] 16.1 24.5 21.4

A general solution would be :

get_predicted_value <- function(p) p[[1]]$data$predicted
get_predicted_value(given_p_object)
#[1] 16.1 24.5 21.4

Upvotes: 1

Related Questions