Oliver Mitchell
Oliver Mitchell

Reputation: 13

Adding smoother to ggplot 2

I have used the following code to create a plot in r using ggplot2:

g <- ggplot(newdata, aes(MVPAper, FMI) +
    geom_smooth(method = 'lm'))

I then added the following:

p <- g + geom_point(aes(color = Age)) + 
     facet_grid(Age ~ .) + 
     stat_smooth(method = 'lm') + 
     theme_bw(base_family = 'Times')`

I am wanting to have a smoother for each of the four graphs I have created, using the facet grid to split the graph into four ages 8,9,12,and 15) can anyone assist with my code?

Upvotes: 0

Views: 79

Answers (1)

jordan
jordan

Reputation: 398

You don't need both geom_smooth() and stat_smooth(). Try this:

library(tidyverse)

df <- diamonds %>% filter(price < 10000, carat < 2.5)

g <- ggplot(df, aes(carat, price, color = cut))

g + 
  geom_point() + 
  geom_smooth(method = 'lm') +
  facet_grid(cut ~ .) + 
  theme_bw()

enter image description here

Upvotes: 1

Related Questions