Format labels produced by cut() as percentages

后端 未结 6 1941
失恋的感觉
失恋的感觉 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:36

    Why not copy the code for cut.default and create your own version with modified levels? See this gist.

    Two lines were changed:

    Line 22: ch.br <- formatC(breaks, digits = dig, width = 1) changed to ch.br <- formatC(breaks*100, digits = dig, width = 1).

    Line 29: else "[", ch.br[-nb], ",", ch.br[-1L], if (right) changed to else "[", ch.br[-nb], "%, ", ch.br[-1L], "%", if (right)

    The rest is the same. And here it is in action:

    library(devtools)
    source_gist(4593967)
    
    set.seed(1)
    x <- runif(100)
    levels(cut2(x, breaks=10))
    #  [1] "(1.24%, 11%]"   "(11%, 20.9%]"   "(20.9%, 30.7%]" "(30.7%, 40.5%]" "(40.5%, 50.3%]"
    #  [6] "(50.3%, 60.1%]" "(60.1%, 69.9%]" "(69.9%, 79.7%]" "(79.7%, 89.5%]" "(89.5%, 99.3%]"
    

提交回复
热议问题