【问题标题】:Combining stat_bin with stat_smooth结合 stat_bin 与 stat_smooth
【发布时间】:2018-01-02 12:42:28
【问题描述】:

我正在使用以下代码生成柱状图:

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')

我想在上面加一条黄土线,但是这段代码:

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

给我一​​个错误:stat_smooth requires the following missing aesthetics: y

如何从 stat_smooth 中访问 stat_bin 的 y 值?

【问题讨论】:

  • 你能提供一个可重现的例子吗?

标签: r ggplot2


【解决方案1】:

我不知道有没有一种方法可以在单个命令中完成。你可以试试这个:

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))

得到

【讨论】:

  • 与其写ggplot_build(p)$data[[1]] ,不如写layer_data(p)。这是官方支持的 API。
  • 感谢@ClausWilke 引起我的注意;我不知道这个功能。
猜你喜欢
  • 1970-01-01
  • 2016-01-07
  • 2019-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多