How to Add Expressions to Labels in Facet_Wrap

How to add expressions to labels in facet_wrap?

In order to do what I asked, first load this labeller function from @Roland first appearing here:

facet_wrap_labeller <- function(gg.plot,labels=NULL) {
#works with R 3.0.1 and ggplot2 0.9.3.1
require(gridExtra)

g <- ggplotGrob(gg.plot)
gg <- g$grobs
strips <- grep("strip_t", names(gg))

for(ii in seq_along(labels)) {
modgrob <- getGrob(gg[[strips[ii]]], "strip.text",
grep=TRUE, global=TRUE)
gg[[strips[ii]]]$children[[modgrob$name]] <- editGrob(modgrob,label=labels[ii])
}

g$grobs <- gg
class(g) = c("arrange", "ggplot",class(g))
g
}

Then save the original ggplot() object:

myplot <- ggplot(mydf, aes(x = x, y = y)) + geom_smooth(method = "lm") + geom_point() + facet_wrap(~ letter, ncol = 2)

Then call facet_wrap_labeller() and feed the expression labels as an argument:

facet_wrap_labeller(myplot, labels = c(expression(paste("A or ", alpha)), expression(beta), expression(gamma), expression(delta)))

The expressions should now appear as the facet_wrap() labels.

Adding expressions to facet labeller in ggplot 2 2.0

There only appear to be 4 labels for 5 facets in your example, but you could use labeller=label_parsed and rename the factor levels fairly easily, avoiding the need for another function.

## Rename levels (I used data.table::melt, so they were characters)
melted$factor <- factor(melted$factor,
levels=paste0('f', 1:5),
labels=c('A', 'B', 'C', '{}^0*italic(D)~plain((rarefied))', 'E'))

p <- ggplot(melted, aes(variable, value)) +
stat_boxplot(geom ='errorbar') +
geom_boxplot()
p + facet_wrap(~factor, labeller=label_parsed)

Sample Image

Expression in ggplot2 facet labels

Looks overly complicated, but works. You'll have to use facet_grid though.

make_label <- function(value) {
x <- as.character(value)
bquote(italic(.(x))~subjects)
}

plot_labeller <- function(variable, value) {
do.call(expression, lapply(levels(value), make_label))
}

ggplot(tips, aes(x=total_bill, y=tip/total_bill)) +
geom_point(shape=1) +
facet_grid(.~sex, labeller = plot_labeller)

Sample Image

R facet labels with expressions using label_parsed

There are two problems - firstly mpg$drv is character, not factor, and secondly, you need to set the factor labels, not the levels. I think this is what you want...

mpg3 <- mpg
mpg3$drv <- factor(mpg3$drv,
levels=c("4","f","r"),
labels=c("4^{wd}","- Front %.% e^{pi * i}","4^{wd} - Front"))

ggplot(mpg3, aes(x=displ, y=hwy)) +
geom_point() +
facet_grid(. ~ drv, labeller = label_parsed)

Sample Image

How to change facet labels?

Change the underlying factor level names with something like:

# Using the Iris data
> i <- iris
> levels(i$Species)
[1] "setosa" "versicolor" "virginica"
> levels(i$Species) <- c("S", "Ve", "Vi")
> ggplot(i, aes(Petal.Length)) + stat_bin() + facet_grid(Species ~ .)

facet_wrap() in ggplot with a combination of math expressions and a string

One approach is to convert id to a factor with levels specified in facet_names and then use label_parsed as the labeller function, interpreting the labels as plotmath expressions:

library(dplyr)
library(ggplot2)

df <- mutate_at(df, .vars = "id", .funs = factor, labels = facet_names)

ggplot(df, aes(x = x)) +
geom_histogram() +
facet_wrap(~ id, labeller = label_parsed)

Sample Image

R : ggplot2 : facet_grid : how include math expressions in few (not all) labels?

Proposed Solution:

Prequisite:

activity <- as.numeric(c("44", "41", "48", "43", "42", "45", 
"44", "39", "47", "68", "88", "57"))
group <- c("first", "first", "first", "first", "first", "first",
"second", "second", "second", "second", "second", "second")
day <- c("0", "0", "0", "20", "20", "20", "0", "0", "0", "20",
"20", "20")
a <- data.frame(activity, group, day)
require(ggplot2)
levels(a$group) <- c("control", expression("100 µg " * .L^"-1" * ""))

Proposed Solution:

p1 <- qplot(day, activity, data = a)
p1 + facet_grid(. ~ group, labeller = label_parsed)

result:

Sample Image

Explanation

We create the labels structure as a string, where we create a formula, noting to use ~ to replace spaces... We then tell facet_grid() to parse the label string passed to it as a formula by setting labeller = label_parsed...

Note: The details of the display are described in ?plotmath, but note that geom_text() and facet_grid() use strings, not expressions.

I hope the above helps.

Reference:

See Hagley Wickham's page on labellers...: https://github.com/hadley/ggplot2/wiki/labeller

How to use labeller = label_parsed to include expressions in some ggplot facet labels?

There are two problems with your code, as far as I can see. First, when you parse the labels you need to replace spaces with the ~ character (this was also noted in the SO question you link). This is what's causing the error you see; the parser can't deal with the whitespace between 'Capped' and 'brood' in your first factor level. Second, you are assigning three factor levels while only two appear in your data.

Changing the first two lines of your 'Code' block to the following produces a correct graph:

df$Trait = as.factor(as.character(df$Trait))
levels(df$Trait) <- c("Capped~brood~cells", expression(sqrt("Colony weight (g)")))

How to add superscripts to facet labels

You want labeller = label_parsed. Here's a simple example

mt = mtcars

mt$facets = factor(mt$cyl, labels = c(
"DO~(mg~L^{-1})",
"Temperature~('°C')",
"Light~(µmol~m^{-2}~s^{-1})"))

ggplot(mt, aes(mpg,cyl)) +
geom_point() +
facet_grid(~facets, labeller = label_parsed)

Sample Image



Related Topics



Leave a reply



Submit