Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrissyhroberts/0d1a96186d54637f8f42bcc750fac77f to your computer and use it in GitHub Desktop.
Save chrissyhroberts/0d1a96186d54637f8f42bcc750fac77f to your computer and use it in GitHub Desktop.
# Example code to extract x and y values from a geom_smooth
library(tidyverse)
#make a dummy data set with 11 observations and increasing number
df<-tibble(month=1:11,
n = c(100,140,200,260,360,470,560,630,770,990,1100))
# make a ggplot object with a geom_smooth()
p <- ggplot(df, aes(month, n))+geom_smooth() +geom_point()
# use ggplot_build to find the code behind the curve - the first element of data in the result is the geom_smooth curve
pp<- ggplot_build(p)$data[[1]]
pp
# plot the data from what we just extracted, to prove the principle.
ggplot(pp,aes(x,y))+geom_line()
# find the floor of each integer on x axis
pp$x<-floor(pp$x)
# remove replicates and select the values of x and y
pp <- pp %>% mutate(dup = duplicated(x)) %>%
filter(dup==FALSE) %>%
select(x,y)
pp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment