【问题标题】:ggplot() scaling with scale::percent_format() producing strange resultsggplot() 使用 scale::percent_format() 缩放会产生奇怪的结果
【发布时间】:2019-04-13 21:35:45
【问题描述】:
library(tidyverse)
mtcars %>% 
  count(cyl) %>% 
  mutate(prop = n / sum(n)) %>% 
  ggplot(aes(x = cyl, y = prop)) + 
  geom_point() + 
  scale_y_continuous(labels = scales::percent_format(accuracy = 5L))

如果我在上面使用scales::percent() 而不是scales::percent_format(accuracy = 5L),我的百分比标签中会出现小数位,这是我不想要的。

问题 - 5L 做什么 在我上面的示例中?为什么我需要使用整数 5L 而不是 5?为什么 6L 将最高 y 值从 40% 变为 42%?这简直太奇怪了。

【问题讨论】:

    标签: r ggplot2 scale


    【解决方案1】:

    首先,它不需要精确地指定为整数(即​​5 工作就可以了)。

    其次,您可以随时在 R 控制台中执行?scales::percent_format(它是免费的!)。这样做会告诉您有关该功能的信息:

    percent_format(
      accuracy = NULL, scale = 100, prefix = "", suffix = "%",
      big.mark = " ", decimal.mark = ".", trim = TRUE, ...
    )
    

    因此,它需要许多可能的参数,所有这些参数都有默认值,有些是选项(通过...)。

    accuracy 参数的默认值为NULL。如果我们在我们看到的功能的帮助页面上向下滚动一点:

    • accuracy:要四舍五入的数字,NULL 用于自动猜测。

    如果我们键入不带括号或? 前缀的函数名,我们可以看到整个源代码。这样做表明它最终调用了scales::number(),其定义为:

    function (x, accuracy = 1, scale = 1, prefix = "", suffix = "", 
              big.mark = " ", decimal.mark = ".", trim = TRUE, ...) {
      if (length(x) == 0) return(character())
      accuracy <- accuracy %||% precision(x)
      x <- round_any(x, accuracy/scale)
      nsmall <- -floor(log10(accuracy))
      nsmall <- min(max(nsmall, 0), 20)
      ret <- format(scale * x, big.mark = big.mark, decimal.mark = decimal.mark, 
                    trim = trim, nsmall = nsmall, scientific = FALSE, ...)
      ret <- paste0(prefix, ret, suffix)
      ret[is.infinite(x)] <- as.character(x[is.infinite(x)])
      ret[is.na(x)] <- NA
      ret
    }
    

    这个:

    accuracy <- accuracy %||% precision(x)
    

    如果accuracy 不是NULL 则使用它,否则使用precision() 函数猜测。

    之后的下一行是您问题的最终答案。

    【讨论】:

      【解决方案2】:

      逗号后5位

      library(ggplot2)
      
      library(tidyverse)
      
      mtcars %>% 
        count(cyl) %>% 
        mutate(prop = n / sum(n)) %>% 
        ggplot(aes(x = cyl, y = prop)) + 
        geom_point() + 
        scale_y_continuous(labels = scales::percent_format(accuracy=.00001))
      

      【讨论】:

        猜你喜欢
        • 2015-10-04
        • 2019-02-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多