lmsimp
lmsimp

Reputation: 932

How to use label_wrap_gen with as_labeller in facet_wrap

I have a facet plot and would like to wrap the facet strip titles over multiple lines (if over a certain number of characters) so I know I use labeller = label_wrap_gen(10) (for say wrapping over 10 characters) and this works great when passed to facet_wrap, however, I also want to pass new labels. I know I can use labeller = as_labeller(new labels) to do this. Is there a way to do both together? I'd prefer not to mess around with the data and re-label them directly in the data.frame (in my own case a tibble).

Here is an example to demonstrate:

data(iris)

## plot iris lengths by species
ggplot(iris, aes(x=Sepal.Length, y=Petal.Length)) + 
  geom_point() + 
  facet_wrap(~Species)

## re-label species names
newLabs <- c(paste("this one is called", levels(iris$Species)))
newLabs <- setNames(newLabs, nm = levels(iris$Species))
ggplot(iris, aes(x=Sepal.Length, y=Petal.Length)) + 
  geom_point() + 
  facet_wrap(~Species, labeller = as_labeller(newLabs))

This produces this: enter image description here

How can I wrap the facet strip titles when also using as_labeller?

sessionInfo
R version 4.0.0 (2020-04-24)
Platform: x86_64-apple-darwin17.0 (64-bit)
Running under: macOS High Sierra 10.13.6

Matrix products: default
BLAS:   /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/4.0/Resources/lib/libRlapack.dylib

locale:
[1] en_GB.UTF-8/en_GB.UTF-8/en_GB.UTF-8/C/en_GB.UTF-8/en_GB.UTF-8

attached base packages:
[1] stats4    parallel  stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
 [1] rsconnect_0.8.16     forcats_0.5.0        stringr_1.4.0        purrr_0.3.4          readr_1.3.1         
 [6] tibble_3.0.1         tidyverse_1.3.0      gtools_3.8.2         dendextend_1.13.4    patchwork_1.0.1     
[11] gridExtra_2.3        plotly_4.9.2.1       pRolocdata_1.26.0    tidyr_1.1.0          reshape2_1.4.4      
[16] pRoloc_1.29.0        BiocParallel_1.22.0  MLInterfaces_1.68.0  cluster_2.1.0        annotate_1.66.0     
[21] XML_3.99-0.3         AnnotationDbi_1.50.0 IRanges_2.22.2       MSnbase_2.14.2       ProtGenerics_1.20.0 
[26] S4Vectors_0.26.1     mzR_2.22.0           Rcpp_1.0.4.6         Biobase_2.48.0       BiocGenerics_0.34.0 
[31] ggplot2_3.3.1        shinyhelper_0.3.2    colorspace_1.4-1     colourpicker_1.0     shinythemes_1.1.2   
[36] DT_0.13              shiny_1.4.0.2        dplyr_1.0.0         

Upvotes: 7

Views: 3547

Answers (1)

MrFlick
MrFlick

Reputation: 206253

You can do

plot(iris, aes(x=Sepal.Length, y=Petal.Length)) + 
  geom_point() + 
  facet_wrap(~Species, labeller = as_labeller(newLabs, default=label_wrap_gen(10)))

enter image description here The as_labeller takes a default labeller function. So you just need to pass the label wrapper there.

Upvotes: 6

Related Questions