8

Given a sample dataset:

size = 10000
dist = seq(0, 10, length.out=size)
cohort.kv = list(A=3,B=40,C=44)
cohort = sample(names(cohort.kv), size, TRUE)
cohort.v = mapply(function(v) cohort.kv[[v]], cohort)
across.kv = list(ONE=1,TWO=2,THREE=3)
across = sample(names(across.kv), size, TRUE)
across.v = mapply(function(v) across.kv[[v]], across)
along.kv = list(FIVE=5, EIGHT=8, ELEVEN=11)
along = sample(names(along.kv), size, TRUE)
along.v = mapply(function(v) along.kv[[v]], along)
df = data.frame(
  dist=dist, cohort=cohort, across=across, along=along,
  value=sin(dist/across.v+cohort.v)*along.v
)
df$across = factor(df$across, levels=names(across.kv))
df$along = factor(df$along, levels=names(along.kv))

I am trying to add latex into the facet labels. This answer explains how to add latex to ggplot labels. The code below produces a faceted ggplot with latex in the axis labels, and modified facet labels.

library(ggplot2)
# install.packages("latex2exp", dependencies=TRUE)
library(latex2exp)
(
  ggplot(df, aes(x=dist, y=value, color=cohort))
  + geom_line()
  + facet_grid(
    rows=vars(across),
    cols=vars(along),
    labeller=labeller(
      across=c(ONE="UNO",TWO="DOS",THREE="TRES"),
      along=c(FIVE=TeX("$V_5$"),EIGHT=TeX("$V_8$"),ELEVEN=TeX("$V_11$"))
    )
  )
  + xlab(TeX("Distance ($\\delta$)"))
  + ylab(TeX("Intensity ($\\alpha$)"))
)

Plot result

The line along=c(FIVE=TeX("$V_5$"),EIGHT=TeX("$V_8$"),ELEVEN=TeX("$V_11$")) should change the top facet labels at the top, but it does not.

How can I add latex to face labels?

1 Answer 1

5

I am sure there is a better way to do this, but one method is to change the levels:

levels(df$across) <- c(ONE="UNO", TWO="DOS", THREE="TRES")
levels(df$along) <- c(FIVE = TeX("$V_5$"), EIGHT = TeX("$V_8$"), ELEVEN = TeX("$V_{11}$"))

Then use label_parsed for labeller:

ggplot(df, aes(x=dist, y=value, color=cohort)) +
 geom_line() +
 facet_grid(
  rows=vars(across),
  cols=vars(along),
  labeller=label_parsed
) +
  xlab(TeX("Distance ($\\delta$)")) +
  ylab(TeX("Intensity ($\\alpha$)"))

label_parsed interprets the labels as plotmath expressions.

Sign up to request clarification or add additional context in comments.

1 Comment

Excellent! I actually prefer this solution to setting up a custom labeller. I wonder what other components have trouble with reading TeX expressions by default.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.