How to change facet labels?

后端 未结 20 1848
既然无缘
既然无缘 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:25

    Note that this solution will not work nicely in case ggplot will show less factors than your variable actually contains (which could happen if you had been for example subsetting):

     library(ggplot2)
     labeli <- function(variable, value){
      names_li <- list("versicolor"="versi", "virginica"="virg")
      return(names_li[value])
     }
    
     dat <- subset(iris,Species!="setosa")
     ggplot(dat, aes(Petal.Length)) + stat_bin() + facet_grid(Species ~ ., labeller=labeli)
    

    A simple solution (besides adding all unused factors in names_li, which can be tedious) is to drop the unused factors with droplevels(), either in the original dataset, or in the labbeler function, see:

    labeli2 <- function(variable, value){
      value <- droplevels(value)
      names_li <- list("versicolor"="versi", "virginica"="virg")
      return(names_li[value])
    }
    
    dat <- subset(iris,Species!="setosa")
    ggplot(dat, aes(Petal.Length)) + stat_bin() + facet_grid(Species ~ ., labeller=labeli2)
    

提交回复
热议问题