Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
354 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...