How to change facet labels?

后端 未结 20 1890
既然无缘
既然无缘 2020-11-22 14:50

I have used the following ggplot command:

ggplot(survey, aes(x = age)) + stat_bin(aes(n = nrow(h3), y = ..count.. / n), binwidth = 10)
  + scale         


        
20条回答
  •  借酒劲吻你
    2020-11-22 15:22

    This solution is very close to what @domi has, but is designed to shorten the name by fetching first 4 letters and last number.

    library(ggplot2)
    
    # simulate some data
    xy <- data.frame(hospital = rep(paste("Hospital #", 1:3, sep = ""), each = 30),
                     value = rnorm(90))
    
    shortener <- function(string) {
      abb <- substr(string, start = 1, stop = 4) # fetch only first 4 strings
      num <- gsub("^.*(\\d{1})$", "\\1", string) # using regular expression, fetch last number
      out <- paste(abb, num) # put everything together
      out
    }
    
    ggplot(xy, aes(x = value)) +
      theme_bw() +
      geom_histogram() +
      facet_grid(hospital ~ ., labeller = labeller(hospital = shortener))
    

提交回复
热议问题