首页 > 解决方案 > 如何在ggplot的文本框中使用LaTeX表达式

问题描述

我有以下ggplot

library(ggplot2)
library(ggtext)
library(ggdist)
library(latex2exp)

set.seed(123)
DF <- rbind(data.frame('Label' = 'A', val = rnorm(200, 5)), 
            data.frame('Label' = 'B', val = rnorm(500, 10)))

ggplot(DF, aes(Label, val)) +
  stat_dots(aes(fill = Label)) +
  geom_textbox(aes(-Inf, -Inf, hjust = 0, vjust = 0, label = parse(text = TeX(r'(\tau)'))), data.frame())

基本上我想在窗口LaTeX内编写语法。这里我举了一个小例子,但在我原来的例子中,我有一个很大的表达。textboxggplotLaTeX

使用上面的代码,我得到以下错误:

Don't know how to automatically pick scale for object of type expression. Defaulting to continuous.
Error: Aesthetics must be valid data columns. Problematic aesthetic(s): label = parse(text = TeX("\\tau")). 
Did you mistype the name of a data column or forget to add after_stat()?

任何如何LaTeXtextboxin中使用的指针ggplot都会非常有帮助。

谢谢你的指点。

标签: rggplot2latexggtext

解决方案


?latex2exp::latex2exp_supported()似乎不包括tau,因此无法将其翻译为plotmath. 一种解决方法是绘制一个空文本框并annotate()在其上放置一个图层,这可以采用 LaTex,正如 Svannoy在此处所建议的那样。

ggplot(DF, aes(Label, val)) +
  stat_dots(aes(fill = Label)) +
  geom_textbox(x= -Inf, y= -Inf, hjust = 0, vjust = 0, label = "") +
  annotate(geom='text',
           x= -Inf, y= -Inf, hjust = 0, vjust = 0,
           label= TeX("    $\\hat{Y} = B_0 + B_1X_1",
                     output='character'), parse = TRUE)

这给出了以下情节。

在此处输入图像描述

但是,仍有一些未解决的问题 - 如何处理不受支持的表达式,例如 tau?

TeX调用的输出是

"paste(' ','',hat(paste('Y')),'',phantom() == phantom(),'B',phantom() [ {paste('0')} ],'',phantom() + phantom(),'B',phantom() [ {paste('1')} ],'X',phantom() [ {paste('1')} ],'')" 

我们可以使用latex2expr另一个annotate. 鉴于,这不是漂亮的代码。

ggplot(DF, aes(Label, val)) +
  stat_dots(aes(fill = Label)) +
  geom_textbox(x= -Inf, y= -Inf, hjust = 0, vjust = 0, label = "") +
  annotate(geom='text',
           x= -Inf, y= -Inf, hjust = 0, vjust = 0,
           label= TeX("    $\\hat{Y} = B_0 + B_1X_1",
                             output='character'), parse = TRUE) +
  annotate(geom = 'text',
           x= -Inf, y= -Inf, hjust = -23.5, vjust = -0.20,
           label = sprintf('%s', "\u03C4"), parse = T)

其中 tau 是 unicode 表示。最后,笨重的部分是调整变量以使其在正确的位置。

用 tau 注释


推荐阅读