Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
546 views
in Technique[技术] by (71.8m points)

r - How to add Latex code in ggplot2 legend labels?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...