How to use earlier declared variables within aes in ggplot with special operators (..count.., etc.)

前端 未结 1 561
情歌与酒
情歌与酒 2020-12-08 16:03

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.         


        
相关标签:
1条回答
  • 2020-12-08 16:26

    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()
    
    0 讨论(0)
提交回复
热议问题