0

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.

dandrews
  • 967
  • 5
  • 18
nadja
  • 1
  • sorry for the images, I couldnt get the code block to work (either) values [1,] 0.1939713 [2,] 0.2042603 [3,] 0.2191685 [4,] 0.2346884 ... the code 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..)) – nadja Aug 09 '23 at 18:06
  • 1
    simply copy your code and set off using ```. Also provide some data. Use `dput(input)` and paste the result assigned to an object – dandrews Aug 09 '23 at 18:07

1 Answers1

2

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`.

stefan
  • 90,330
  • 6
  • 25
  • 51