Edit emmeans' arrow plot's facet text

Viewed 103

I'm trying to edit the facet label's text produced by emmean's arrow plot using ggplot2's syntax to override the default.

pigs.lm <- lm(log(conc) ~ source + as.factor(percent),
 data = pigs)
    
pigs.plot <- plot(emmeans(pigs.lm , specs = "percent", by="source"), comparison = T)

enter image description here

protein_names <- list('source: fish'="Source: Fish",
                      'source: soy'="Source: Soybean",
                      'source: skim'="Source: Skim milk")

I got an error at this step. How do I fix it?

pigs.plot + facet_wrap(~ source, labeller = protein_names)

Error in cbind(labels = list(), list(`{`, if (!is.null(.rows) || !is.null(.cols)) { :  number of rows of matrices must match (see arg 2)

I tried facet_grid, too, but no luck.

3 Answers

You were almost there. (1) You need a named vector (I think), not a list; (2) the names of the list should match the elements of the faceting variable, not the already-labeled values (i.e. the strip labels).

pp <- unlist(protein_names)
names(pp) <- gsub("source: ","", names(pp))
pigs.plot + facet_wrap(~ source, labeller = labeller(source = pp), ncol = 1)

You could also construct your labels correctly in the first place this way:

capwords <- function(x) gsub("^([a-z])", "\\U\\1", x, perl=TRUE)
s <- levels(pigs$source)
protein_names <- setNames(sprintf("Source: %s", capwords(s)), s)

You can try this too:

#Custom labels

custom_labels <- as_labeller(function(x){
     return(paste0("Source: ", c("Fish", "Soybean", "Skim milk")))
})

#Making a plot

pigs.plot + facet_wrap(~ source, labeller = custom_labels, strip.position = "right", ncol = 1)

enter image description here

Seems to me that in many cases where a custom plot is desired, it is more straightforward just to start basically from scratch:

plotdat <- plot(emmeans(...), comp = TRUE, plotit = FALSE)

Now you have a data frame with every value that is needed to construct the plot. So now plot this information in the way you like, perhaps adding or modifying columns in plotdat first.

Related