How to add Latex code in ggplot2 legend labels?

后端 未结 2 2020
遇见更好的自我
遇见更好的自我 2020-12-03 18:59

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\         


        
相关标签:
2条回答
  • 2020-12-03 19:23


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

    0 讨论(0)
  • 2020-12-03 19:32

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

    0 讨论(0)
提交回复
热议问题