A nice post was recently published on the rsnippets blog, about the tikzDevice R package. This package is – indeed – awesome. Even if it has been removed from the CRAN website. Of course, it can be download from the archive folder, on http://cran.r-project.org/…, but also (for a more recent version) on http://download.r-forge.r-project.org/…. But first, it is necessary to install the following package.
> install.packages("filehash")
Then, we download on of the tikzDevice.zip files, and load it, e.g. using (on Mac)
Then, we can load the library
> library("tikzDevice")
If we want to use nice LaTeX formulas, it might be necessary to upload some (LaTeX) libraries and to specify the encoding format
> "options(tikzMetricPackages = c("\\usepackage[utf8]{inputenc}", + "\\usepackage[T1]{fontenc}", "\\usetikzlibrary{calc}", "\\usepackage{amssymb}"))
(this is detailed, e.g. in http://yihui.name/…), then, we write a code to plot a graph. The idea is to produce a tex file which contains the graph, or more precisely which will produce a pdf graph when we compile it. We start with
> tikz("normal-dist.tex", width = 8, height = 4, + standAlone = TRUE, + packages = c("\\usepackage{tikz}", + "\\usepackage[active,tightpage,psfixbb]{preview}", + "\\PreviewEnvironment{pgfpicture}", + "\\setlength\\PreviewBorder{0pt}", + "\\usepackage{amssymb}"))
We will produce a 8×4 graph. The graph is the following,
> u=seq(-3,3,by=.01) > plot(u,dnorm(u),type="l",axes=FALSE,xlab="",ylab="",col="white") > axis(1) > I=which((u>=0)&(u<=1)) > polygon(c(u[I],rev(u[I])),c(dnorm(u)[I],rep(0,length(I))),col="red",border=NA) > lines(u,dnorm(u),lwd=2,col="blue")
We can add text (or TeX based text)
> text(-1.5, dnorm(-1.5)+.17, "$\\textcolor{blue}{X\\sim\\mathcal{N}(0,1)}$", cex = 1.5) > text(1.75, dnorm(1.75)+.25, + "$\\textcolor{red}{\\mathbb{P}(X\\in[0,1])=\\displaystyle{\\int_0^1 \\varphi(x)dx}}$", cex = 1.5)
And we end the file with a standard
> dev.off()
This will produce a .tex file. If we compile this file, we can generate a pdf file, that can be inserted in lecture notes, slides or articles,
Nice, isn’t it ?
OpenEdition suggests that you cite this post as follows:
Arthur Charpentier (May 3, 2013). LaTeX in R graphs. Freakonometrics. Retrieved December 7, 2024 from https://doi.org/10.58079/ouq9
Nice. Too bad it doesn’t work for R-3.0.0… Tried building from the github repository, but will need more work than I can do…
yes, I am still using my old 2.15 version,