How to annotate() ggplot with latex

前端 未结 3 637
青春惊慌失措
青春惊慌失措 2020-12-13 09:19

I\'d like to add latex text to a ggplot2 plot using annotate(). Using expression(), as described here for adding latex to axis labels, does not see

3条回答
  •  没有蜡笔的小新
    2020-12-13 09:43

    The tikzDevice package is back on CRAN (latest version 0.9 published Nov 2015).

    Using tikz does require a full LaTeX installation; it may be easiest to do via knitr within a LaTeX document (just set dev="tikz" in the chunk options). However, you can use it to create a standalone figure as well. Ironically, the hardest part of this question was getting a text subscript, which requires an additional LaTeX package (fixltx2e) for the \textsubscript command ...

    library(tikzDevice)
    ## add a package to the defaults
    options(tikzLatexPackages=
                c(getOption("tikzLatexPackages"),"\\usepackage{fixltx2e}"))
    tikz("tikz.tex",standAlone=TRUE)
    library("ggplot2"); theme_set(theme_bw())
    p <- ggplot(mpg, aes(x=cty, y=hwy)) + geom_point() +
      scale_x_continuous(name="text\\textsubscript{subscript}")
    p + annotate("text", x=10, y=40, label="text\\textsubscript{subscript}")
    dev.off()
    
    system("pdflatex tikz.tex")
    

提交回复
热议问题