Home > OS >  Adding labels to the geom_bar
Adding labels to the geom_bar

Time:04-19

I have some difficulties with the labels for this chart. Specifically, the labels do not fit in their corresponding bar. Also, it looks like the labels are not in a right place. In other words, the percentage for non-Hispanic Whites should appear in the orange boxes.

Thanks,

MRR

IDD_line_race <-
  ggplot(race_2010, aes(x =Year_  , y =per_X_ , fill=race_new2), colour="black",
         stat="identity", width=0.9,  position = position_dodge())  
  geom_col()  
  geom_text(aes(y = per_X_, label = paste0(format(per_X_),"%")), colour = "white") 
  scale_fill_manual(values=c("#F76900","#000E54"))   
  labs(
    x = "Year",
    y = "Population 65  (%)",
    caption = (""),
    face = "bold"
  )  
  theme_classic() 
  coord_flip()

IDD_line_race

CodePudding user response:

The issue is that geom_col by default uses position = "stack" while geom_text uses position="identity". To put your labels at the correct positions you have to use position = "stack" or the more verbose position = position_stack() in geom_text too. Additionally I right aligned the labels using hjust=1 and removed the clutter from the ggplot() call.

Using some fake example data:;

library(ggplot2)

set.seed(123)

race_2010 <- data.frame(
  Year_ = rep(2010:2019, 2),
  race_new2 = rep(c("non-Hispanic Black", "non-Hispanic White"), each = 10),
  per_X_ = round(c(runif(10, 1, 2), runif(10, 9, 12)), 1)
)

ggplot(race_2010, aes(x =Year_  , y =per_X_ , fill=race_new2))  
  geom_col()  
  geom_text(aes(y = per_X_, label = paste0(format(per_X_),"%")), colour = "white", position = position_stack(), hjust = 1)  
  scale_fill_manual(values=c("#F76900","#000E54"))   
  labs(
    x = "Year",
    y = "Population 65  (%)",
    caption = (""),
    face = "bold"
  )  
  theme_classic() 
  coord_flip()

  • Related