Adding percentages up to two decimals on to of ggplot bar chart

Viewed 62

I was wondering if anyone knows how to put the labels of the magnitudes/measurements as percentages up to two decimals in a ggplot bar chart.

Right now this is what I got: enter image description here

df <- data.frame(Seller=c("Ad","Rt","Ra","Mo","Ao","Do"), 
                Avg_Cost=c(5.30,3.72,2.91,2.64,1.17,1.10), Num=c(6:1))
str(df)
plotB <- ggplot(df, aes(x = reorder(Seller, Avg_Cost), y = Avg_Cost)) + 
  geom_col( width = 0.7) + 
  coord_flip() + 
  geom_bar(stat="identity", fill="steelblue") + 
  theme( panel.background = element_blank(), axis.title.x = element_blank(),
         axis.title.y = element_blank()) +
  geom_text(aes(label=Avg_Cost), size=5, hjust=-.2 ) + 
  ylim(0,6)
plotB

My desired output should show the labels like 5.30%, 3.72%, 2.91% ....

I tried using : geom_text(aes(label=scales::percent( ), y= ), size=6, hjust=-.2 )

the problem is that it gives me three decimals no matter how I round it. Thanks in advance.

1 Answers

Just use sprintf:

sprintf("%0.2f%%", df$Avg_Cost)
# [1] "5.30%" "3.72%" "2.91%" "2.64%" "1.17%" "1.10%"

plotB <- ggplot(df, aes(x = reorder(Seller, Avg_Cost), y = Avg_Cost)) + 
  geom_col( width = 0.7) + 
  coord_flip() + 
  geom_bar(stat="identity", fill="steelblue") + 
  theme( panel.background = element_blank(), axis.title.x = element_blank(),
         axis.title.y = element_blank()) +
  geom_text(aes(label = sprintf("%0.2f%%", Avg_Cost)), size=5, hjust=-.2 ) + 
  ###                   ^^^^ this is your change ^^^^
  ylim(0,6)

enter image description here

Related