How to change facet labels?

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

    I feel like I should add my answer to this because it took me quite long to make this work:

    This answer is for you if:

    • you do not want to edit your original data
    • if you need expressions (bquote) in your labels and
    • if you want the flexibility of a separate labelling name-vector

    I basically put the labels in a named vector so labels would not get confused or switched. The labeller expression could probably be simpler, but this at least works (improvements are very welcome). Note the ` (back quotes) to protect the facet-factor.

    n <- 10
    x <- seq(0, 300, length.out = n)
    
    # I have my data in a "long" format
    my_data <- data.frame(
      Type = as.factor(c(rep('dl/l', n), rep('alpha', n))),
      T = c(x, x),
      Value = c(x*0.1, sqrt(x))
    )
    
    # the label names as a named vector
    type_names <- c(
      `nonsense` = "this is just here because it looks good",
      `dl/l` = Linear~Expansion~~Delta*L/L[Ref]~"="~"[%]", # bquote expression
      `alpha` = Linear~Expansion~Coefficient~~alpha~"="~"[1/K]"
      )
    
    
    ggplot() + 
      geom_point(data = my_data, mapping = aes(T, Value)) + 
      facet_wrap(. ~ Type, scales="free_y", 
                 labeller = label_bquote(.(as.expression(
                   eval(parse(text = paste0('type_names', '$`', Type, '`')))
                   )))) +
      labs(x="Temperature [K]", y="", colour = "") +
      theme(legend.position = 'none')
    

提交回复
热议问题