label position in stat_bin for geom_histogram: how to adress ..count.. in the position_nudge method?

84 Views Asked by At

I've got input_values as a tibble: input_values

For these alues I'd like to plot a histogram, where the columns are labeled (90° angle, almost directly on top of the colums).

as_tibble(input_values) %>% ggplot(aes(x = values) + geom_histogram(stat = "bin") + stat_bin(geom='text', angle = 90, family = "Calibri", hjust=-1, vjust=0.4, aes(label=..count..))

[this is the result (plus a bit styling)](https://i.stack.imgur.com/bvjDu.png)

the label is always positioned too high. I reckon something like "stat_bin(..., position = position_nudge(y = ..count..*-0.1)) would do the trick. But I cannot address my count values in this manner, for the x it seems to work, see here

I tried also stat = count, position = position_nudge(y = 1000) etc. but it didn't work because the labels are more further up, the higher the count was.

1

There are 1 best solutions below

0
stefan On

The issue is that you have set hjust=-1. As you rotated your labels set hjust=0 to align the labels with the top of the bars, then use position = position_nudge(...) to shift them. Also note that I use after_stat instead of the .. notation as the latter was deprecated in ggplot2 >= 3.4.0.

Using some fake random example data:

library(ggplot2)

set.seed(123)

input_values <- data.frame(
  values = rnorm(3e6)
)

ggplot(input_values, aes(x = values)) +
  geom_histogram(stat = "bin") +
  stat_bin(
    geom = "text", angle = 90, family = "Calibri",
    hjust = 0, position = position_nudge(y = 1000),
    aes(label = after_stat(count))
  )
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.