Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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))
like image 345
rjen Avatar asked Oct 28 '25 15:10

rjen


1 Answers

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

like image 71
r2evans Avatar answered Oct 31 '25 05:10

r2evans