如何在 ggplot2 图形的轴标签中引用 siunitx 单位?

How to reference siunitx units in axis labels for ggplot2 figures?

我有一个 knitr Rnw 文件(带有嵌入式 R 的 LaTeX)导入 siunitx 包。我用 \DeclareSIUnit 声明单位,我想在我的 ggplot() 图中引用轴标签中的这些单位。我已经尝试了 latex2enc 的 master 分支,但它没有满足我的需要。有帮助吗?

最小工作示例:

\documentclass{article}
\usepackage{siunitx}
\DeclareSIUnit{\dunit}{\SIUnitSymbolDegree Du}
\begin{document}
    <<setup, include=TRUE>>=
    library(ggplot2)
    @

    This first plot with a changed Y label should work.

    <<new-y-label, echo=TRUE>>=
    ggplot(iris, aes(Sepal.Length, Petal.Length)) + geom_line(aes(linetype=Species)) + ylab("Petal length")
    @

    I can change the label to include basic \LaTeX\ commands using the latex2exp package, which is not formally released for R version 3.4.4.

    <<latex-y-label, echo=TRUE>>=
    # devtools::install_github('stefano-meschiari/latex2exp')
    library(latex2exp)
    ggplot(iris, aes(Sepal.Length, Petal.Length)) + geom_line(aes(linetype=Species)) + ylab(TeX("$\alpha$"))
    @

    But how do I change the Y label to reference \si{\dunit} ?

    <<does-not-work, echo=TRUE>>=
    ggplot(iris, aes(Sepal.Length, Petal.Length)) + geom_line(aes(linetype=Species)) + ylab(TeX("$\si{\dunit}$"))
    @

    This does not work.  Help!
\end{document}

我最后也在 RStudio 社区上问了我的问题:https://community.rstudio.com/t/how-to-reference-siunitx-units-in-axis-labels-for-ggplot2-figures/8038/8

我得到了两个答案,这两个答案都产生了有用的输出,但我认为最好的答案是 baptiste 的最后一个答案。编译时间有不小的增加,但正确使用了宏,作为奖励,图中使用了与文档其余部分相同的字体。这是我的 MWE 的修改版本:

\documentclass{article}
\usepackage{siunitx}
\DeclareSIUnit{\dunit}{\SIUnitSymbolDegree Du}
\begin{document}
    <<setup, include=TRUE>>=
    library(ggplot2)
    @

    <<works-and-looks-good-too, echo=TRUE, dev='tikz'>>=
    library(tikzDevice)
    ggplot(iris, aes(Sepal.Length, Petal.Length)) + geom_line(aes(linetype=Species)) + ylab("$\si{\dunit}$")
    @

\end{document}