如何将变量传递给ggplot aes / ..y ..函数

时间:2018-05-21 03:34:26

标签: r ggplot2

我正在考虑将transform传递到下面的函数中以便能够排列辅助轴...但是,我收到错误:

Error in y * transform : non-numeric argument to binary operator

library(ggplot2)
a.samples <- rbeta(10000, 25, 75)
b.samples <- rbeta(10000, 35, 65)

df <- data.frame(x = b.samples/a.samples)

p <- ggplot(df, aes(x = x)) + geom_histogram(fill = 'grey50', alpha = .6)

transform <- max(ggplot_build(p)$data[[1]]$ymax)

p + geom_line(aes(y = ..y.. * transform), stat='ecdf') + # error here
    geom_vline(xintercept = 1, linetype = 'dashed') +
    scale_y_continuous(sec.axis = sec_axis(~./transform, name = "ecdf")) +
    guides(color = FALSE)

如果我明确地将值1260写入aes参数,它就可以工作。

...geom_line(aes(y = ..y.. * 1260), stat='ecdf')...

2 个答案:

答案 0 :(得分:1)

能够将其与aes_string

一起使用
p + geom_line(aes_string(y = paste0('..y.. * ', transform)), stat='ecdf') + 
    geom_vline(xintercept = 1, linetype = 'dashed') +
    scale_y_continuous(sec.axis = sec_axis(~./transform, name = "ecdf")) +
    guides(color = FALSE)

答案 1 :(得分:1)

所以你上面的代码奇怪地为我工作,没有任何其他错误,除了binwidths关闭所以我不知道是什么产生错误但我只是通过添加stat_ecdf()

调整它
library(ggplot2)
a.samples <- rbeta(10000, 25, 75)
b.samples <- rbeta(10000, 35, 65)

df <- data.frame(x = b.samples/a.samples)

p <- ggplot(df, aes(x = x)) + geom_histogram(fill = 'grey50', alpha = .6)

transform <- max(ggplot_build(p)$data[[1]]$ymax)
transform
p + stat_ecdf(aes(y = ..y.. * transform),geom = "line") + 
  geom_vline(xintercept = 1, linetype = 'dashed') +
  scale_y_continuous(sec.axis = sec_axis(~./transform, name = "ecdf")) +
  guides(color = FALSE)