【问题标题】:Adding percentages up to two decimals on to of ggplot bar chart在 ggplot 条形图上添加最多两位小数的百分比
【发布时间】:2021-08-18 05:30:53
【问题描述】:

我想知道是否有人知道如何在 ggplot 条形图中将幅度/测量值的标签以百分比形式放置到小数点后两位。

现在这是我得到的:

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)

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

【问题讨论】:

    标签: r ggplot2 statistics bar-chart


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-05
      • 2022-01-09
      • 1970-01-01
      相关资源
      最近更新 更多