Combining stat_bin with stat_smooth

2019-08-04 06:24发布

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?

标签: r ggplot2
1条回答
劫难
2楼-- · 2019-08-04 07:28

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

enter image description here

查看更多
登录 后发表回答