Combining stat_bin with stat_smooth

2019-08-04 06:27发布

问题:

I am using the following code to generate a histogram bar plot:

library(ggplot2)

set.seed(123)
dt <- data.frame(SurveyDate = sample(1:500, 1000, replace = TRUE))

ggplot(dt, aes(SurveyDate)) + stat_bin(bins = 50) + ylab('Survey Responses')

I would like to add a LOESS line on top of it, but this code:

ggplot(dt, aes(SurveyDate)) + stat_bin(bins = 50) + ylab('Survey Responses') +
  stat_smooth(aes(SurveyDate, ..count..), method='loess')

Gives me an error: stat_smooth requires the following missing aesthetics: y

How can I access the y value from stat_bin, from within stat_smooth?

回答1:

I don't know that there's a way to do it in a single command. You could try this:

library(ggplot2)

set.seed(123)
dt <- data.frame(SurveyDate = sample(1:500, 1000, replace = TRUE))
p <- ggplot(dt, aes(SurveyDate)) + 
  stat_bin(bins = 50) +
  ylab('Survey Responses')
dat <- layer_data(p)
p +
  stat_smooth(data = dat, aes(x, y))

to get



标签: r ggplot2