ggplot() 缩放 scale::percent_format() 产生奇怪的结果

ggplot() scaling with scale::percent_format() producing strange results

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%?这太奇怪了。

首先,它不需要精确地指定为整数(即​​ 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() 函数猜测。

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

逗号后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))