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?
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() .
ggplot2 allows you to do data manipulation, such as filtering or slicing, within the data argument.
To customize the plot, the following arguments can be used: alpha, color, dotsize and fill. Learn more here: ggplot2 dot plot.
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'.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With