2
votes

I am trying to add loess smoothing to my grouped line graph in ggplot that I have created using geom_line(stat='count').

This is a similar question, but the answer did not work with a grouping variable: Combining stat_bin with stat_smooth

p = ggplot(mtcars, aes(x=cyl, colour=factor(vs))) + 
  geom_line(stat = 'count') 

dat <- layer_data(p)
p + stat_smooth(data = dat, aes(x, y))

I want a smoothing line for each group. Using the above code I get the error: Error in factor(vs) : object 'vs' not found

1

1 Answers

1
votes

By default, stat_smooth inherits unspecified aesthetics from the original plot, in this case colour. But colour refers to vs, which isn't a variable in the new dat data frame, hence the error. All you need to do though, is tell it what the new grouping variable is, in this case, colour. Note that I'm adding method="lm", se=FALSE as well because there's just not enough data points here for the default smooth.

p <- ggplot(mtcars, aes(x=cyl, colour=factor(vs))) + 
  geom_line(stat = 'count') 
dat <- layer_data(p)
p + stat_smooth(data = dat, aes(x, y, colour=colour), 
                method="lm", se=FALSE)

enter image description here

You'll notice, though, that the colors don't match, because the variables don't match. I suspect the cleanest way to deal with this will be to get the counts ahead of time in a new data frame and then to use that in the plotting.

library(tidyverse)
mtcars %>% mutate_at(vars(cyl, vs), factor) %>%
  group_by(cyl, vs) %>% summarize(n=n()) %>%
ggplot() + aes(x=cyl, y=n, colour=vs, group=vs) +
  geom_line() +
  stat_smooth(method="lm", se=FALSE)

enter image description here