简体   繁体   中英

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? 演示

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM