0
votes

The below produces a plot with value labels - from a table containing percentages; NOT raw individual level data. So the stat="identity" argument is used. How would you instruct ggplot to add a % symbol to each value label above the bar in such a case?

#Generate data table
Percent<-c(20,80)
row_labels<-c("Male","Female")
df<-data.frame(row_labels,Percent)

#Plot data table
ggplot(df) + aes(row_labels,Percent,fill=row_labels) + geom_bar(stat="identity") +  
labs(x = "",title = " ") + theme(legend.title = element_blank()) + coord_flip()+ theme(legend.position="none") + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),  
panel.background = element_blank(), axis.line = element_blank(), axis.ticks.y = element_blank(), axis.title.x=element_blank(), axis.text.x=element_blank(), axis.ticks.x=element_blank()) + geom_text(aes(label=round(Percent,digits=1)), hjust = -0.15, size = 3)
1
Try with label = paste(round(Percent, digits=1), "%")) in geom_text.markus
Unfortunately it just moves the labels away from the tops of the bars to the axis, not sure why. Perhaps the coord_flip() is confusing it.CK7

1 Answers

0
votes

I have modified aes of the geom_text in the following way:

ggplot(df, aes(row_labels,Percent,fill=row_labels) ) +
 geom_bar(stat="identity") +  
 geom_text(aes(y=Percent+5, label = paste(Percent, "%")) ) + 
 labs(x = "",title = " ") +
 theme(
  legend.position="none",
  legend.title = element_blank(),
  panel.grid.major = element_blank(),
  panel.grid.minor = element_blank(),  
  panel.background = element_blank(),
  axis.line = element_blank(),
  axis.ticks.y = element_blank(),
  axis.title.x=element_blank(),
  axis.text.x=element_blank(),
  axis.ticks.x=element_blank()
 ) + 
 coord_flip() 

Although the order of layers/adjustments does not matter (you have mentioned coord_flip), I have reorganised the code for better fluency.