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))
Run Code Online (Sandbox Code Playgroud)
如果我使用scales::percent()上面而不是scales::percent_format(accuracy = 5L)在我的百分比标签中得到小数位,这是我不想要的。
问题 - 5L在我上面的例子中做了什么?为什么我需要使用整数 5L 而不是 5?为什么 6L 将最高 y 值从 40% 更改为 42%?这简直太奇怪了。
逗号后 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))
Run Code Online (Sandbox Code Playgroud)
首先,它不需要被精确指定为整数(即5工作得很好)。
其次,您可以?scales::percent_format随时在 R 控制台中执行操作(它是免费的!)。这样做可以告诉您有关该函数的信息:
percent_format(
accuracy = NULL, scale = 100, prefix = "", suffix = "%",
big.mark = " ", decimal.mark = ".", trim = TRUE, ...
)
Run Code Online (Sandbox Code Playgroud)
因此,它需要许多可能的参数,所有参数都有默认值,有些是选项(通过...)。
该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
}
Run Code Online (Sandbox Code Playgroud)
这:
accuracy <- accuracy %||% precision(x)
Run Code Online (Sandbox Code Playgroud)
表示如果accuracy不NULL使用它,否则通过使用该precision()函数进行猜测。
之后的下一行是您问题的最终答案。
| 归档时间: |
|
| 查看次数: |
10673 次 |
| 最近记录: |