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 = TRUE)
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.
CodePudding user response:
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)
CodePudding user response:
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)