How to change facet labels?

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

    Adding another solution similar to @domi's with parsing mathematical symbols, superscript, subscript, parenthesis/bracket, .etc.

    library(tidyverse)
    theme_set(theme_bw(base_size = 18))
    
    ### create separate name vectors
    # run `demo(plotmath)` for more examples of mathematical annotation in R
    am_names <- c(
      `0` = "delta^{15}*N-NO[3]^-{}",
      `1` = "sqrt(x,y)"
    )
    
    # use `scriptstyle` to reduce the size of the parentheses &
    # `bgroup` to make adding `)` possible 
    cyl_names <- c(
      `4` = 'scriptstyle(bgroup("", a, ")"))~T~-~5*"%"',
      `6` = 'scriptstyle(bgroup("", b, ")"))~T~+~10~degree*C',
      `8` = 'scriptstyle(bgroup("", c, ")"))~T~+~30*"%"'
    )
    
    ggplot(mtcars, aes(wt, mpg)) + 
      geom_jitter() +
      facet_grid(am ~ cyl,
                 labeller = labeller(am  = as_labeller(am_names,  label_parsed),
                                     cyl = as_labeller(cyl_names, label_parsed))
                 ) +
      geom_text(x = 4, y = 25, size = 4, nudge_y = 1,
                parse = TRUE, check_overlap = TRUE,
                label = as.character(expression(paste("Log"["10"], bgroup("(", frac("x", "y"), ")")))))
    

    ### OR create new variables then assign labels directly
    # reverse facet orders just for fun
    mtcars <- mtcars %>% 
      mutate(am2  = factor(am,  labels = am_names),
             cyl2 = factor(cyl, labels = rev(cyl_names), levels = rev(attr(cyl_names, "names")))
      )
    
    ggplot(mtcars, aes(wt, mpg)) + 
      geom_jitter() +
      facet_grid(am2 ~ cyl2,
                 labeller = label_parsed) +
      annotate("text", x = 4, y = 30, size = 5,
               parse = TRUE, 
               label = as.character(expression(paste("speed [", m * s^{-1}, "]"))))
    

    Created on 2019-03-30 by the reprex package (v0.2.1.9000)

    0 讨论(0)
  • 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))
    

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

    The labeller function defintion with variable, value as arguments would not work for me. Also if you want to use expression you need to use lapply and can not simply use arr[val], as the argument to the function is a data.frame.

    This code did work:

    libary(latex2exp)
    library(ggplot2)
    arr <- list('virginica'=TeX("x_1"), "versicolor"=TeX("x_2"), "setosa"=TeX("x_3"))
    mylabel <- function(val) { return(lapply(val, function(x) arr[x])) }
    ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width)) + geom_line() + facet_wrap(~Species, labeller=mylabel)
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2020-11-22 15:25

    Simple solution (from here):

    p <- ggplot(mtcars, aes(disp, drat)) + geom_point()
    # Example (old labels)
    p + facet_wrap(~am)
    
    
    to_string <- as_labeller(c(`0` = "Zero", `1` = "One"))
    # Example (New labels)
    p + facet_wrap(~am, labeller = to_string)
    
    0 讨论(0)
  • 2020-11-22 15:28

    Here's another solution that's in the spirit of the one given by @naught101, but simpler and also does not throw a warning on the latest version of ggplot2.

    Basically, you first create a named character vector

    hospital_names <- c(
                        `Hospital#1` = "Some Hospital",
                        `Hospital#2` = "Another Hospital",
                        `Hospital#3` = "Hospital Number 3",
                        `Hospital#4` = "The Other Hospital"
                        )
    

    And then you use it as a labeller, just by modifying the last line of the code given by @naught101 to

    ... + facet_grid(hospital ~ ., labeller = as_labeller(hospital_names))
    

    Hope this helps.

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