0
votes

I would like to add relative frequency label to the bins of a histogram made by ggplot() function. I tried use geom_text() but I couldn't calculate the bin relative frequency and also I couldn't adequalty map the text to the top bins.

Any help woul be much apprechiated.

Here is a reproductible example:

df_CK <- data.frame(id = c(1:36), ck = c(121, 82, 100, 151, 68, 58, 95, 145, 64, 199, 101, 163,
       84, 57, 139, 60, 78, 94, 119, 104, 110, 113, 118, 203, 62, 83, 67, 93, 92, 110, 25, 123, 70, 48, 95, 42))

ggplot(df_CK, aes(x = ck, y = ..density..)) +
  geom_histogram(breaks = c(20, 40, 60, 80, 100, 120, 140, 160, 200, 220), fill = "coral1", colour = "grey60", size = .2) +
  theme(plot.title = element_text(size = 5, face = "bold", hjust = 0.5)) +
  theme_classic() +
  theme_bw(base_line_size = 0, base_rect_size = 0.25, base_size = 6) +
  ylab("Densidade") +
  scale_x_continuous(limits = c(0, 216), breaks = seq(0, 216, 9))
  # geom_text(aes(x = ck, label = ..prop.., y = ..density..),
  #           position = position_dodge(width = .5), vjust = -0.5, size = 2)

Best, Hellen

1
Add stat = "bin" to geom_text? - Axeman
@Axeman, I don't undersand where I can put this argument into geom_text to obtein relative frequencies to each bin. Please, can you give me a example? Thank you. - Hellen Geremias

1 Answers

1
votes

Use the same stat between both geoms. Then use the calculated statistics listed in the documentation.

For example:

br <- c(20, 40, 60, 80, 100, 120, 140, 160, 200, 220)
ggplot(df_CK, aes(ck, stat(density))) +
  geom_histogram(breaks = br) +
  geom_text(
    aes(label = round(stat(count) / sum(stat(count)), 2)), 
    stat = 'bin', vjust = -1, breaks = br
  )

enter image description here