Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Customize facet_wrap plot label in R?

I’m creating a facet_wrap plot in R, and I’m trying to automate the labeller. I can create a custom label manually, using this code:

library(ggplot2)
library(tidyverse)
df <- data.frame(a = rep(c(1/8,1/4,1/2), each = 100),
                 b = rep(c("A", "B", "C", "D"), each = 25),
                 x = rnorm(100))


names <- c(
  `0.125` = "alpha~`=`~1/8",
  `0.25` = "alpha~`=`~1/4",
  `0.5` = "alpha~`=`~1/2"
)

df %>% ggplot() +
  geom_density(aes(x = x, colour = b))+
  facet_wrap(~a, labeller = labeller(a = as_labeller(names, label_parsed)))

The above code produces this plot:

facetplot

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

As you can see I’m creating the custom names in the names variable and then passing that to the labeller argument. I want to come up with a way to automate this process. So I can use any vector of names. Any suggestions?

>Solution :

I think I have a possible solution. If a user supplies a personalised vector of values, say, vec <- c(1/5, 'Hello', 3.14) then Im looping through each value of vector and pasting the unicode value for alpha and turning it into a list. After this I am creating a kind of dummy function that contains my new list of label titles and Im passing that to the labeller function:

nam <- NULL
  for(i in 1:(length(vec))){
    nam[i] <-  list(paste0('\u03b1',"=", vec[i]))
  }
 
  custLab <- function (x){
    nam
  } 

  p <- df %>% ggplot() +
    geom_density(aes(x = x, colour = b))+
    facet_wrap(~a, labeller = as_labeller((custLab)))
  

This produces the following:
solutionPlot

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading