18

Let's say I want to plot histogram with the following formula (I know it's not the best but it will illustrate the problem):

set.seed(1)
dframe <- data.frame(val=rnorm(50))
p <- ggplot(dframe, aes(x=val, y=..count..))
p + geom_bar()

It works just fine. However let's say that we want for some reason frequencies divided by an earler defined number. My shot would be:

k <- 5
p <- ggplot(dframe, aes(x=val, y=..count../k))
p + geom_bar()

However I get this annoying error:

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

Does there exist a way for using both ..count..-like variables with some predefined ones?

4

1 回答 1

31

ggplot()当您使用某些功能进行绘图时,似乎存在一些功能错误stat(例如y=..count..)。函数ggplot()已经有environment变量,所以它可以使用在这个函数之外定义的变量。

例如,这将起作用,因为k仅用于更改x变量:

k<-5
ggplot(dframe,aes(val/k,y=..count..))+geom_bar()

这将产生错误,因为k用于更改y使用 stat 计算的值y=..count..

k<-5
ggplot(dframe,aes(val,y=..count../k))+geom_bar()
Error in eval(expr, envir, enclos) : object 'k' not found

要解决这个问题,你可以kaes().

k <- 5
ggplot(dframe,aes(val,k=k,y=..count../k))+geom_bar()
于 2013-07-24T11:32:56.403 回答