Format labels produced by cut() as percentages

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

    A new answer to an oldish question.

    You could use the label argument to pass a function to format the labels. I will use gsubfn and scales::percent

    library(gsubfn)
    library(scales)
    pcut <- function(x) gsubfn('\\d\\.\\d+', function(x) percent(as.numeric(x)),xx)
    d <- data.frame(x=runif(100))
    
    ggplot(d,aes(x=x,y=seq_along(x))) + 
     geom_point(aes(colour = cut(x, breaks = 10))) + 
     scale_colour_brewer(name = 'x', palette = 'Spectral', label = pcut)
    

    enter image description here

提交回复
热议问题