Search code examples
rggplot2cutnotation

Change the label notation styles in cut functions?


I'm using the set of ggplot2 functions for creating some binned data in R. The notation style is "(a,b]". I know that's possible to use pre-specified labels. But I like the idea of using the returned numeric labels provided in the default. However, I'd like to change the notation style to something like "a - b". Is this possible?


Solution

  • You can rename the levels from cut automatically using regex

    x = runif(100, 0,100)
    y = cut(x, breaks = (0:10)*10)
    levels(y)
    # [1] "(0,10]"   "(10,20]"  "(20,30]"  "(30,40]"  "(40,50]"  "(50,60]"  "(60,70]"  "(70,80]" 
    # [9] "(80,90]"  "(90,100]"
    levels(y) = sub(".(.+),(.+).", "\\1-\\2"  , levels(y))
    # [1] "0-10"   "10-20"  "20-30"  "30-40"  "40-50"  "50-60"  "60-70"  "70-80"  "80-90"  "90-100"