Search code examples
rdataframeggplot2geom-bar

Auto adjust in the middle text in bar


I have a data frame called df :


df = tibble(var =c("A","B","C","D","E"), val = c(2,8,9,1,5) );df

resulting to :

 var     val
  <chr> <dbl>
1 A         2
2 B         8
3 C         9
4 D         1
5 E         5

I want to plot horizontally the bars of the val column and the value of each category to be in text in the middle of the bar.

ggplot(df, aes(x = var, y = val)) +
  geom_bar(stat = "identity", fill = "lightgrey") +
  coord_flip() + # This flips the coordinates to make the bars horizontal
  geom_text(aes(label = val))

resulting to:

enter image description here

How can I put the values (text) automatically in the middle of the horizontal bar ?


Solution

  • You can put the labels into the middle of the bars using position = position_stack(vjust = .5):

    library(ggplot2)
    
    ggplot(df, aes(x = val, y = var)) +
      geom_bar(
        stat = "identity",
        fill = "lightgrey"
      ) +
      geom_text(
        aes(label = val),
        position = position_stack(vjust = .5)
      )