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

Pet*_*etr 1 r ggplot2 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)
Run Code Online (Sandbox Code Playgroud)

Gre*_*gor 5

这是内置于scales::percent. 有一个accuracy参数被描述为“要四舍五入的数字”。

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)
Run Code Online (Sandbox Code Playgroud)

  • @Petr,尽可能友好地,当您知道某个参数并且它似乎不起作用时,请查看文档。“准确度”的解释是我在答案中引用的内容,“要舍入的数字”,如果您滚动到帮助页面底部的示例部分,示例的前几行说明了“准确度”的使用` 参数,对比 `accuracy = 0.001` 和 `accuracy = 0.5`。 (3认同)