# Is it possible to use a calculated-aesthetic variable for a label?

#1

I want to use stat(max(count)) for a label but I'm getting this error, I'm not sure if this is possible. Can any one help me to clarify this?

``````library(ggplot2)
library(dplyr)

iris %>%
ggplot(aes(x = Petal.Width)) +
geom_histogram() +
geom_label(x = 1, y = 20, label = stat(max(count)))
#> Error in max(count): 'type' (closure) de argumento no válido
``````

Created on 2018-09-23 by the reprex package (v0.2.1)

#3

What are you trying to do with `stat(max(count)))`? Count the number of appearances for each species?

#4

The `count` variable is computed by the `bin` stat. SO you want to use
that statistic with a `text` geom like this:

``````library(ggplot2)

ggplot(iris, aes(x = Petal.Width)) +
geom_histogram() +
stat_bin(geom = "text", aes(label = stat(count)))
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
``````

If you just want to show the max count, you could use something like this,

``````ggplot(iris, aes(x = Petal.Width)) +
geom_histogram() +
stat_bin(geom = "text",
aes(label = stat(ifelse(count == max(count), count, NA))))
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
#> Warning: Removed 29 rows containing missing values (geom_text).
``````

Created on 2018-09-23 by the reprex package (v0.2.0).

#5

@eliocamp Thanks, the later was what I was looking for, I just have to change "text" by "label" and voilà!