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?

Roland
  • 127,288
  • 10
  • 191
  • 288
kuba
  • 1,005
  • 2
  • 11
  • 16

1 Answers1

31

It seems that there is some bug with ggplot() function when you use some stat for plotting (for example y=..count..). Function ggplot() has already environment variable and so it can use variable defined outside this function.

For example this will work because k is used only to change x variable:

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

This will give an error because k is used to change y that is calculated with stat y=..count..

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

To solve this problem you can kefine k inside the aes().

k <- 5
ggplot(dframe,aes(val,k=k,y=..count../k))+geom_bar()
Didzis Elferts
  • 95,661
  • 14
  • 264
  • 201
  • 1
    @DidzisElferts That would have never occured to me. I was ready to post an answer using `get`. – Roland Jul 24 '13 at 11:57
  • 1
    @kuba `p <- ggplot(dframe, aes(x=val, y=..count../get("k", envir=.GlobalEnv)))` – Roland Jul 24 '13 at 12:05
  • I think there's a bug to be honest; ggplot() has an `environment` parameter, but it seems to be ignored when stat variables are used – baptiste Jul 24 '13 at 12:14
  • @baptiste It seems so because code ggplot(dframe,aes(val/k,val))+geom_point() works without problems – Didzis Elferts Jul 24 '13 at 12:16
  • @DidzisElferts one sometimes finds problems with scope when ggplot() is called within a function, but usually using environment works. Here it doesn't. – baptiste Jul 24 '13 at 12:50
  • This is brilliant. This is either a bug or just poorly documented (surprising because I generally find ggplot documentation superb). Either way, excellent to know. – Spencer Oct 30 '13 at 02:07