【问题标题】:Choose type of ggplot2 histogram (frequency or density) within a function在函数中选择 ggplot2 直方图的类型(频率或密度)
【发布时间】:2017-03-11 14:17:29
【问题描述】:

长期阅读者,第一次提问者...我有一个函数,可以输入数据并输出具有某些特定格式的 ggplot2 直方图。我正在尝试编辑此函数,以便函数参数之一可以指定我是否希望直方图显示数据的频率或密度。我知道我可以分别在aes(y=..count..)aes(y=..density..)geom_histogram() 函数中手动指定它。但是如果不直接输入这些变量,我在弄清楚如何访问这些变量时遇到了问题。

这是我正在尝试做的简化版本:

library(ggplot2)

histplot <- function(data,density=FALSE) {

  if (density) {
    type <- "..density.."
  } else {
    type <- "..count.."
  }

  theplot <- ggplot(data, aes(x=data[,1])) +
    geom_histogram(position="identity",binwidth = 2, 
               aes(y=eval(parse(text=type))))

  g <- ggplot_gtable(ggplot_build(theplot))
  grid.draw(g)

}

xy <- data.frame(X=rnorm(100,0,10),Y=rnorm(100))
histplot(xy)

当我执行这个函数时,我得到的错误是:

Error in eval(expr, envir, enclos) : object '..count..' not found

我不知道为什么这不起作用,因为如果我执行以下操作:

x <- 1:5
y <- "x"
eval(parse(text=y))

那么输出就是

[1] 1 2 3 4 5

我的猜测是它与环境有关。

【问题讨论】:

  • @Elin 如果您有一个名为string 的变量,那么eval(parse(text="string")) 将获取字符串"string" 并执行具有相同名称的变量

标签: r ggplot2 histogram


【解决方案1】:

我相信你可以在这种情况下使用aes_string,所以这样的东西应该可以工作

type="..count.."
ggplot(xy, aes_string(x=xy[,1], y=type)) +
  geom_histogram(position="identity",binwidth = 2)

【讨论】:

  • 好像可以了,谢谢!你能解释一下为什么我尝试的方法不起作用,为什么会这样吗?
  • @LindsayLee 这与标准和非标准评估有关。使用 aes_string() 意味着您可以将参数作为带引号的字符串传递,而 aes() 需要不带引号的对象。看看adv-r.had.co.nz/Computing-on-the-language.html 作为一般经验法则,如果您发现自己在使用eval(parse()),那么有更好的方法!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-30
  • 2020-08-08
  • 2015-02-21
相关资源
最近更新 更多