3
votes

I've found and been guided to numerous post showing how to place stats above all bars in a barplot in ggplot, but I haven't found one that shows how to only show the count/percentage above only one bar in the barplot.

For example with the following plot:

ggplot(mtcars, aes(x = gear)) + geom_bar() +
  geom_text(stat='count',aes(label=..count..),vjust=-1)

mtcars barplot

how could I just print "12" above the middle bar and supress printing "5" and "15". The bar I'd like to show the count above will vary from plot to plot (e.g. in another plot I'd like to show the stat above the 4th largest out of 5 bars).

2
That post and one it references only addresses putting values above all the bars. I would like to print those values only above specific bar in the barplot.Russ Thomas
It's pretty much a duplicate of the cited link and two part questions are not encouraged on SO. So It's also probably a duplicate as well and I'd encourage you to search for one and document your search before making any further appeal. You are expected to search before posting questions.IRTFM
@42, revised per your suggestions. Thanks for the guidance.Russ Thomas
Use a vector that contains "" for the positions where you don't want values. And ... What about "How do I manually set geom_bar fill color in ggplot"?IRTFM

2 Answers

3
votes

You can use stat() to calculate the count and define any condition you want for geom_text()

library(ggplot2)
library(dplyr)

# Select the gear with the second highest count
g <- mtcars %>% group_by(gear) %>% summarise(n = n()) %>% arrange(rev(n)) %>% .[2, 1]

ggplot(mtcars, aes(x = gear)) +
    geom_bar() +
    geom_text(stat='count',
          aes(label=stat(ifelse(x == !!g, count, NA))), # Apply condition
          color = "blue",
          vjust=-1) +
    NULL

Created on 2018-10-13 by the reprex package (v0.2.1)

2
votes

I couldn't find one that use geom_text r geom_bar but the examples in ?annotate seemed pretty straighforward>

ggplot(mtcars, aes(x=gear, group = gear)) + geom_bar(fill=c("red", "green","blue")) + 
     annotate("text", x=4, y = 13, label = "12")