12

Consider the following example:

p <- ggplot(data = data.frame(A=c(1,2,3,4,5,6,7,8),B=c(4,1,2,1,3,2,4,1),C=c("A","B","A","B","A","B","A","B")))
p <- p + geom_line(aes(x = A, y = B,color = C))

I would like to change the labels in the legend from "A" and "B" to Latex formulae, say "$A^h_{t-k}$" and "$B^h_{t-k}$", respectively.

Apparently, according to the answers here, ways to achieve this exist. However, I am really struggling to get it to work. Could somebody break it down for me?

k88074
  • 2,042
  • 5
  • 29
  • 43

2 Answers2

21

To use real LaTeX syntax, you can use the latex2exp package. Note the use of unname(), this is necessary.

library(ggplot2)
library(latex2exp)
df <- data.frame(A = c(1,2,3,4,5,6,7,8),
                 B = c(4,1,2,1,3,2,4,1),
                 C = c("A","B","A","B","A","B","A","B")
)
ggplot(df) + 
  geom_line(aes(x = A, y = B,color = C)) +
  scale_color_discrete(labels = unname(TeX(c("$A_{t-k}^h$", "$B_{t-k}^h$"))))

Created on 2018-05-29 by the reprex package (v0.2.0).

Rory Nolan
  • 972
  • 10
  • 15
  • 6
    This worked great, though slight caveat for `\foo` calls. I had to use `TeX("$\\Delta")` in my code. Just a heads up that double `\\` escapes may be necessary. – Hendy Oct 29 '19 at 18:48
  • "Note the use of unname(), this is necessary." Why – jessexknight Apr 24 '20 at 17:17
  • 1
    (Perhaps already-inferred after all this time...) Likely because when `labels=` is given a _named_ vector of values, it tries to associate the names in the `values=` argument with actual values in the data aesthetic. For example, using RoryNolan's code, if we instead use `names(.)`, we see that `TeX` returns a named vector with names `c("$A_{t-k}^h$", "$B_{t-k}^h$")`. Those names do not appear in the raw data, so they will not be applied to the data values `"A"` and `"B"` appropriately. One could replace `unname(.)` with `setNames(., c("B","A"))` instead for a similar (though reversed) result. – r2evans Mar 23 '23 at 02:03
7


library(ggplot2)
df <- data.frame(A = c(1,2,3,4,5,6,7,8),
                 B = c(4,1,2,1,3,2,4,1),
                 C = c("A","B","A","B","A","B","A","B")
                 )
ggplot(df) + 
    geom_line(aes(x = A, y = B,color = C)) +
    scale_color_discrete(labels = c(expression(A[t-k]^h), expression(B[t-k]^h)))

GGamba
  • 13,140
  • 3
  • 38
  • 47
  • This did not work for axis titles for me. Is there a way to accomplish that? So `scale_x_continuous(expression(\Delta))`, for example? – Hendy Oct 29 '19 at 18:48
  • 1
    `scale_x_continuous(expression(Delta))` does work for me – GGamba Oct 30 '19 at 11:13
  • Ah, excellent. I will give this a try. Now that I see the reply, apologies on not directly just checking the package. It probably states that something like `\` is not required and I just didn't understand. Thanks for the prompt correction! – Hendy Oct 31 '19 at 20:11