Search code examples
rggplot2geom-text

Bounding position for geom_text()


I am making several instances of a tilted bar chart. As the sizes of count and the differences in percent vary, part of one of the labels (count) is pushed outside the bar in some instances. I need the labels to be entirely inside the bar in all instances. If not repositioned to fit inside the bar, I need the labels to be centered as is.

enter image description here

The code is:

library(tidyverse)
library(ggplot2)

data <- tibble(type = c('Cat', 'Dog'),
               group = c('Pets', 'Pets'),
               count = c(10000, 990000),
               percent = c(1, 99))

ggplot(data, aes(x = group, y = percent, fill = type)) +
  geom_bar(stat = 'identity', 
           position = position_stack(reverse = TRUE)) +
  coord_flip() +
  geom_text(aes(label = count),
            position = position_stack(vjust = 0.5, 
                                      reverse = TRUE))

Solution

  • Use hjust="inward":

    ggplot(data, aes(x = group, y = percent, fill = type)) +
      geom_bar(stat = 'identity', position = position_stack(reverse = TRUE)) +
      coord_flip() +
      geom_text(aes(label = count), hjust = "inward", position = position_stack(vjust = 0.5, reverse = TRUE))
    

    enter image description here