如何使用latex来注释()ggplot

Dre*_*een 32 r ggplot2

我想将乳胶文本添加到ggplot2图中annotate().使用expression(),描述在这里添加乳胶轴标签,似乎并没有工作.以机智:

# Use expression() to create subscripted text
p <- ggplot(mpg, aes(x=cty, y=hwy)) + geom_point() +
  scale_x_continuous(expression(text[subscript])) 

# But expression() in annotate adds nothing to the plot
p + annotate("text", x=10, y=40, label=expression(text[subscript])) 

# Passing regular text to annotate works fine
p + annotate("text", x=10, y=40, label="foo") 
Run Code Online (Sandbox Code Playgroud)

为什么expressions的处理方式annotate与其他ggplot函数不同?我怎样才能用乳胶注释?

Geg*_*naV 35

有一个R叫做的包latex2exp可能会有所帮助.它具有TeX接受一些用美元符号括起来的LaTeX表达式的函数,$如下例所示:

library(latex2exp)
library(ggplot2)

qplot(1, "A")+
     ylab(TeX("Formula: $\\frac{2hc^2}{\\lambda^\\beta}$"))+
     xlab(TeX("$\\alpha$"))
Run Code Online (Sandbox Code Playgroud)

例

这个小插图中可以找到更多的例子.

  • 您的示例适用于标签,但问题是关于注释.您的示例不适用于我的注释层,但是,如果您指定output ='character'并将'parse = TRUE'添加到注释调用中,它会执行.`annotate(geom ='text',x = 3,y = 3,label = Tex("$ \\ hat {Y} = B_0 + B_1X_1",output ='character'),parse = TRUE)` (9认同)

Mat*_*rde 17

您可以使用parse参数,而无需expression:

p + annotate("text", x=10, y=40, label="text[subscript]", parse=TRUE)
Run Code Online (Sandbox Code Playgroud)


Ben*_*ker 10

tikzDevice包背在CRAN(最新版本0.9发布2015年11月).

使用tikz确实需要完整的LaTeX安装; knitr在LaTeX文档中进行最简单的操作(只需dev="tikz"在块选项中设置).但是,您也可以使用它来创建独立的数字.具有讽刺意味的是,这个问题最困难的部分是获取文本下标,这需要一个额外的LaTeX包(fixltx2e)来执行\textsubscript命令......

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")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述