在 ggplot 条形图上添加最多两位小数的百分比

问题描述

我想知道是否有人知道如何在 ggplot 条形图中将幅度/测量值的标签作为最多两位小数的百分比。

在这就是我得到的:

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

我想要的输出应该显示像 5.30%、3.72%、2.91% ....

我尝试使用: geom_text(aes(label=scales::percent( ),y= ),size=6,hjust=-.2 )

问题是无论我如何四舍五入,它都会给我三位小数。 提前致谢。

解决方法

只需使用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