Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

scope

r

ggplot2

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?

like image 314
kuba Avatar asked Jul 24 '13 11:07

kuba


People also ask

What does AES do in ggplot?

aes() is a quoting function. This means that its inputs are quoted to be evaluated in the context of the data. This makes it easy to work with variables from the data frame because you can name those directly. The flip side is that you have to use quasiquotation to program with aes() .

Can you filter data in ggplot?

ggplot2 allows you to do data manipulation, such as filtering or slicing, within the data argument.

Which argument of ggplot can be used to add customization to plots?

To customize the plot, the following arguments can be used: alpha, color, dotsize and fill. Learn more here: ggplot2 dot plot.

What is the difference between ggplot and ggplot2?

You may notice that we sometimes reference 'ggplot2' and sometimes 'ggplot'. To clarify, 'ggplot2' is the name of the most recent version of the package. However, any time we call the function itself, it's just called 'ggplot'.


1 Answers

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()
like image 118
Didzis Elferts Avatar answered Oct 26 '22 09:10

Didzis Elferts