r - 如何在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
内编写语法。这里我举了一个小例子,但在我原来的例子中,我有一个很大的表达。textbox
ggplot
LaTeX
使用上面的代码,我得到以下错误:
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()?
任何如何LaTeX
在textbox
in中使用的指针ggplot
都会非常有帮助。
谢谢你的指点。
解决方案
?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 表示。最后,笨重的部分是调整变量以使其在正确的位置。
推荐阅读
- python-3.x - 在 Python 中对数据框进行部分重采样
- http - 在 Flask 请求中更改标头的最佳做法是什么?
- vim - Vim 高级替换
- javafx - JavaFX:调整画布大小无法正常工作
- python-3.x - 使用 PyPDF2 解压缩 PDF FlateDecode 过滤器注释
- java - 带有斜杠的 Spring Boot Json 反序列化
- php - 显示 PHP 选择连接的 LDAP 服务器
- reactjs - Flatlist scrollToIndex 与 Hooks useRef
- angular - 如何使用 WSL 在 Dropbox 目录中开发 Angular 项目?
- python - 检查Linux程序是否停止运行