代码之家  ›  专栏  ›  技术社区  ›  stackinator Brenton Wiernik

ggplot()按比例缩放::百分比\格式()产生奇怪的结果

  •  0
  • stackinator Brenton Wiernik  · 技术社区  · 7 年前
    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%?真奇怪。

    2 回复  |  直到 7 年前
        1
  •  4
  •   hrbrmstr    7 年前

    首先,它不需要精确地指定为整数(即。 5 作品 很好 ).

    第二,你能做到 ?scales::percent_format 在R控制台中的任何时候(它是免费的!)。这样做可以告诉您有关函数的信息:

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

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

    的默认值 accuracy NULL

    • 精确 :要四舍五入的数字, 无效的

    如果我们键入的函数名没有parens或 ? 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)
    

    精确 不是 使用它,否则通过使用 precision() 功能。

    接下来的一行是你问题的最终答案。

        2
  •  9
  •   paoloeusebi    7 年前

    逗号后的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))
    
    推荐文章