【问题标题】:How to always have fixed number of decimals in ggplot - geom_text [duplicate]如何在ggplot中始终具有固定的小数位数-geom_text [重复]
【发布时间】:2019-12-18 16:46:17
【问题描述】:

我需要有固定的小数位数(在这种情况下是两个),但我无法让它工作, 我知道使用 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)

【问题讨论】:

  • 一个相当奇怪的“黑客”:geom_text(aes(label=paste0(round(..count../sum(..count..) ,4) * 100,"%")), stat='count',vjust = -0.5, size = 4)

标签: r ggplot2 geom-text


【解决方案1】:

这是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)

【讨论】:

  • 我注意到percent 已“退休”,label_percent 等价物是什么?(用于学习目的)
  • 谢谢 - 我知道准确性参数,我只是不知道诀窍是让它不是accuracy =3,而是0.03
  • @NelsonGon Ugh.. 这么多 API 更改。据我所知,这适用于scales::percentscales::percent_format。看起来新的scales::label_percent 是函数式的,所以用法可能是label = label_percent(accuracy = 0.01)(..count../sum(..count..)),但我没有更新我的包进行测试。
  • @Petr,当您知道某个参数但它似乎不起作用时,请尽可能好心地查看文档。 accuracy 的解释是我在答案中引用的“要舍入的数字”,如果您滚动到帮助页面底部的示例部分,前几行示例说明了 @987654333 的使用@参数,对比accuracy = 0.001accuracy = 0.5
  • 我试过了,但它抱怨关闭和复制。不过,文档中的用法几乎相同。
【解决方案2】:

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)

【讨论】:

    【解决方案3】:

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

    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%"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-09
      相关资源
      最近更新 更多