Format labels produced by cut() as percentages

后端 未结 6 1957
失恋的感觉
失恋的感觉 2021-02-05 10:21

I need to apply cut on a continuous variable to show it with a Brewer color scale in ggplot2, as in Setting breakpoints for data with scale_fill_brewer() function i

6条回答
  •  野性不改
    2021-02-05 10:28

    The new {santoku} package now offers a way to do this in the development version:

    library(santoku)
    
    set.seed(20200607)
    x <- runif(20)
    
    chop_evenly(x, 10, labels = lbl_intervals(fmt = percent))
    #>  [1] [33.13%, 42.11%) [60.08%, 69.06%) [69.06%, 78.04%) [69.06%, 78.04%)
    #>  [5] [87.02%, 96%]    [6.193%, 15.17%) [15.17%, 24.15%) [6.193%, 15.17%)
    #>  [9] [33.13%, 42.11%) [6.193%, 15.17%) [87.02%, 96%]    [51.1%, 60.08%) 
    #> [13] [42.11%, 51.1%)  [6.193%, 15.17%) [42.11%, 51.1%)  [6.193%, 15.17%)
    #> [17] [6.193%, 15.17%) [69.06%, 78.04%) [78.04%, 87.02%) [87.02%, 96%]   
    #> 9 Levels: [6.193%, 15.17%) [15.17%, 24.15%) ... [87.02%, 96%]
    tab_evenly(x, 10, labels = lbl_intervals(fmt = scales::label_percent(accuracy = 0.1)))
    #> x
    #>  [6.2%, 15.2%) [15.2%, 24.2%) [33.1%, 42.1%) [42.1%, 51.1%) [51.1%, 60.1%) 
    #>              6              1              2              2              1 
    #> [60.1%, 69.1%) [69.1%, 78.0%) [78.0%, 87.0%) [87.0%, 96.0%] 
    #>              1              3              1              3
    

    Created on 2020-06-09 by the reprex package (v0.3.0)

提交回复
热议问题