I have a knitr
Rnw file (LaTeX with embedded R) which imports the siunitx
package. I declare units with \\DeclareSIUnit
and I would like to reference those units in axis labels in my ggplot()
figures. I have tried the master branch of latex2enc
but it does not do what I need. Help?
Minimum working example:
\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}
I ended up asking my question on RStudio Community as well: https://community.rstudio.com/t/how-to-reference-siunitx-units-in-axis-labels-for-ggplot2-figures/8038/8
I got two answers, both of which generated useful output, but in my opinion the best answer was the last one by baptiste. There is a non-trivial increase in compilation time, but the macros are used correctly and as a bonus the same font is used in the figure as in the rest of the document. Here is a modified version of my 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}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.