How to change facet labels?

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

    After struggling for a while, what I found is that we can use fct_relevel() and fct_recode() from forcats in conjunction to change the order of the facets as well fix the facet labels. I am not sure if it's supported by design, but it works! Check out the plots below:

    library(tidyverse)
    
    before <- mpg %>%
      ggplot(aes(displ, hwy)) + 
      geom_point() +
      facet_wrap(~class)
    before
    

    after <- mpg %>%
      ggplot(aes(displ, hwy)) + 
      geom_point() + 
      facet_wrap(
        vars(
          # Change factor level name
          fct_recode(class, "motorbike" = "2seater") %>% 
            # Change factor level order
            fct_relevel("compact")
        )
      )
    after
    

    Created on 2020-02-16 by the reprex package (v0.3.0)

    0 讨论(0)
  • 2020-11-22 15:37

    Just extending naught101's answer -- credit goes to him

    plot_labeller <- function(variable,value, facetVar1='<name-of-1st-facetting-var>', var1NamesMapping=<pass-list-of-name-mappings-here>, facetVar2='', var2NamesMapping=list() )
    {
      #print (variable)
      #print (value)
      if (variable==facetVar1) 
        {
          value <- as.character(value)
          return(var1NamesMapping[value])
        } 
      else if (variable==facetVar2) 
        {
          value <- as.character(value)
          return(var2NamesMapping[value])
        } 
      else 
        {
          return(as.character(value))
        }
    }
    

    What you have to do is create a list with name-to-name mapping

    clusteringDistance_names <- list(
      '100'="100",
      '200'="200",
      '300'="300",
      '400'="400",
      '600'="500"
    )
    

    and redefine plot_labeller() with new default arguments:

    plot_labeller <- function(variable,value, facetVar1='clusteringDistance', var1NamesMapping=clusteringDistance_names, facetVar2='', var1NamesMapping=list() )
    

    And then:

    ggplot() + 
      facet_grid(clusteringDistance ~ . , labeller=plot_labeller) 
    

    Alternatively you can create a dedicated function for each of the label changes you want to have.

    0 讨论(0)
提交回复
热议问题