tikzDevice
The accepted answer is one easy way to get scalable graphics from R to LaTeX.
It does not, IMHO, answer the actual question, since it does not export the figure "directly" (which I interpret to mean "LaTeX-readable code").
Disclaimer: My answer is mostly just a more beginner friendly version of this answer.
To achieve our objective, we can use the R library tikzDevice.
To install it, just use install.packages("tikzDevice")
inside RStudio.
In your R script
library(tikzDevice)
tikz('figs/simpleEx.tex',width=3.5,height=3.5)
plot(1,main='Hello World!')
dev.off()
This will save the output of install.packages("tikzDevice")
to the subdirectory figs
(you have to create the subdirectory in advance) under the name simpleEx.tex
.
Don't forget dev.off()
, since it closes the device, which is what you want to do.
In your LaTeX document
\documentclass{article}
% All LaTeX documents including
% tikz() output must use this
% package!
\usepackage{tikz}
\begin{document}
\begin{figure}[!h]
\centering
% The output from tikz()
% is imported here.
\input{simpleEx.tex}
\caption{Simple Example}
\end{figure}
\end{document}
A quick word about paths
Don't forget that you can set a relative or absolute path for \input{}
, so if you have saved your figures to /projectdirectoy/rdirectory/figs/simpleEx.tex
, but your LaTeX file is in /projectdirectory/latexdirectory/latex.tex
, you can use \input{../rdirectory/figs/simpleEx.tex}
. But of course you can just save the figures directly in your latex directory in the first place, if you wish to do so, by modifiying the tikz('figs/simpleEx.tex',width=3.5,height=3.5)
line to tikz('../latexdirectory/figs/simpleEx.tex',width=3.5,height=3.5)
, for example.
More examples
I have stolen the code examples from the vignette for tikzDevice, where you can find more examples, some of them more elaborate.
sagetex
can be found by searching this site, for example, this post on statistics.\includegraphics{foo.pdf}
(assuming you are using pdflatex or xelatex or lualatex) use eps if you are using classic latex.