如何在 ggplot 中始终具有固定的小数位数 - geom_text

How to always have fixed number of decimals in ggplot - geom_text

我需要有固定的小数位数(在本例中为两位),但我无法让它工作, 我知道使用 roundaccuracy 函数,但它似乎对我不起作用

代码:

library(ggplot2)

ggplot(mtcars, aes(factor(cyl))) + 
  geom_bar(color = "steelblue", fill = "#00AFBB", na.rm = T) +
  scale_fill_discrete(drop=FALSE) +
  scale_x_discrete(drop=FALSE) +
  geom_text(aes(label=scales::percent(round(..count../sum(..count..),4))),
            stat='count',vjust = -0.5, size = 4)

我会自己动手并创建一个函数:

percent2 <- function(x, accuracy = 2){
    paste0(round(100 * x, digits = accuracy), "%")
}

set.seed(123)
percent2(runif(1), accuracy = 0:5)
# "29%"       "28.8%"     "28.76%"    "28.758%"   "28.7578%"  "28.75775%"

这是 scales::percent 的内置功能。有一个 accuracy 参数被描述为 "the number to round to".

ggplot(mtcars, aes(factor(cyl))) + 
  geom_bar(color = "steelblue", fill = "#00AFBB", na.rm = T) +
  scale_fill_discrete(drop=FALSE) +
  scale_x_discrete(drop=FALSE) +
  geom_text(aes(label=scales::percent(..count../sum(..count..), accuracy = 0.01)),
            stat='count',vjust = -0.5, size = 4)

scales::percent 有一个 accuracy 参数。

library(ggplot2)

ggplot(mtcars, aes(factor(cyl))) + 
  geom_bar(color = "steelblue", fill = "#00AFBB", na.rm = T) +
  scale_fill_discrete(drop=FALSE) +
  scale_x_discrete(drop=FALSE) +
  geom_text(
    aes(label=scales::percent(round(..count../sum(..count..),4), accuracy = 0.01)),
        stat='count',vjust = -0.5, size = 4)