3

I want to use ggplot to make a histogram using percentages. I found this answer that gets me part of the way there.

However, I also want to place a label at the top of each histogram bar showing the actual percentage.

Here is my code and a link to the output:

p <- ggplot(mtcars, aes(x = hp)) +  
        geom_bar(aes(y = (..count..)/sum(..count..)), binwidth = 25) + 
        ## scale_y_continuous(labels = percent_format()) #version 3.0.9
        scale_y_continuous(labels = percent) #version 3.1.0
p <- p + stat_bin(aes(label=round((..count..)/sum(..count..),2)), geom="text", size=4)
plot(p)

Here is the output: image

Unfortunately, you can see that the data labels are placed at the non-percentage locations and the bars are "smushed" down.

Is there a way to change the stat_bin parameters so that the text labels actually show up inside or immediately on top of the percentage bars (so that my bars aren't smushed)?

Thank you!

Community
  • 1
  • 1
pdanese
  • 2,187
  • 4
  • 15
  • 21

2 Answers2

2

You'll want to just set the y values for your labels as well (and also make sure you're using the same bins are you are for the bars)

library(scales)
p <- ggplot(mtcars, aes(x = hp)) +  
        geom_bar(aes(y = (..count..)/sum(..count..)), binwidth = 25) + 
        scale_y_continuous(labels = percent_format()) #version 3.0.9
        ##scale_y_continuous(labels = percent) #version 3.1.0
p <- p + stat_bin(aes(y=(..count..)/sum(..count..), 
    label=round((..count..)/sum(..count..),2)), 
    geom="text", size=4, binwidth = 25, vjust=-1.5)
plot(p)
MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • Perfect. Thank you. I didn't realize you could specify the y value in addition to the label value. Thanks again. – pdanese Dec 21 '14 at 22:06
0

When using geom_bar() with binwidth you will currently get following error:

geom_bar() no longer has a binwidth parameter. Please use geom_histogram() instead.

I modified MrFlick's code by including geom_histogram() and by displaying the values to be shown as percentage (instead of fractions) using paste0 function.

library(scales)
p <- ggplot(mtcars, aes(x = hp)) +  
  geom_histogram(aes(y = (..count..)/sum(..count..)), binwidth = 25) +
      stat_bin(aes(y=(..count..)/sum(..count..), 
             label=paste0(round((..count..)/sum(..count..)*100,1),"%")), 
             geom="text", size=4, binwidth = 25, vjust=-1.5)
plot(p)

Output: