Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add Latex code in ggplot2 legend labels?

Tags:

r

ggplot2

latex

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?

like image 260
k88074 Avatar asked Jun 01 '17 14:06

k88074


2 Answers

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).

like image 115
Rory Nolan Avatar answered Oct 20 '22 05:10

Rory Nolan



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)))

like image 6
GGamba Avatar answered Oct 20 '22 05:10

GGamba