0

I need to show bin length on top of each bar but stat_bin is not showing what I expected, I am giving a simple data set which has the same problem which I face with my big data set, please help me to show bin length on top of each bin and if possible then explain its working please

Code without bin length on top of it

library(ggplot2)
data <- data.frame(Brand = c('A', 'B', 'c', 'A'), ct = c(5, 4,3, 4), col = c('X', 'Y', 'X', 'X'))
ggplot(data, aes( Brand,ct, fill=col)) + geom_bar(stat="identity")

enter image description here

Now I want to show 9 on top of A, 4 on top of B and 3 on top of C bar but its showing me error

ggplot(data, aes( Brand,ct, fill=col)) + geom_bar(stat="identity") + stat_bin()

Error: stat_bin() must not be used with a y aesthetic.

I am using minimum parameters in this example code to describe my issue. I don't want to summarize the data before plotting, I am expecting if ggplot have some in-build feature as its already showing aggregate data in graph and its just matter of showing values.

This is not duplicate as I want to explore in-build ggplot mechanism to show the sum, I need to show multiple layer within a bin (fill=col), if I summarize in advance then I may loose this record.

Vineet
  • 1,492
  • 4
  • 17
  • 31

1 Answers1

2

It is highly recommended you summarize your data first before you plot. However, if for whatever reason you didn't want to do that you could do:

ggplot(data, aes( Brand,ct, fill=col)) + geom_bar(stat="identity") + 
      geom_text(aes(y =ave(ct, Brand, FUN = sum), label=ave(ct, Brand, FUN = sum)))

enter image description here

I would not recommend this way however, since it actually plots the "9" twice (which is why it's darker than the other numbers). Using this method there is no way to get around it because your aes needs to be the same length of the data. This means that you cant simply plot c(9,4,3) you need to plot c(9,9,4,3).

Mike H.
  • 13,960
  • 2
  • 29
  • 39