# Plotting R boxplots with pgfplots

I use quite a number of boxplots in my writing, and have chosen pgfplots as my plotting solution for a number of reasons (one of which is the benefit of having the data to build the plot in the tex file itself).

The state of affairs regarding boxplots in pgfplots 1.8+ has improved a lot since I first started using them, but since I normally use R for analysing my data, and since this strikes me as a relatively common setup, I was wondering how people did it, to see if we can come to a common best approach.

tl;dr: If you use R and pgfplots, how do you make your boxplots?

-
pgfplots is a must? You can also build the plot in the tex file itself using R without pgfplots with Sweave. –  Fran Oct 6 '13 at 15:34
Definitely not a must, but I prefer to keep a unified visual aesthetic for my plots throughout my document, and I've found I can achieve this more easily by using the same tool for everything. That said, I've never actually got Sweave to work, so that might have factored into this. An example would be a welcome addition! :P –  jja Oct 6 '13 at 15:37
Done. See my answer. –  Fran Oct 6 '13 at 15:57

This is what I've started using recently, since understanding more or less how to use the new boxplot interface of pgfplots. Although I know it's not particularly pretty (how could it be? I'm by no means an R programmer...), it does get the job done. But it would be interesting to see what others have come up with.

pgfbp <- function (bp, options=c()) {
for (c in 1:ncol(bp$stats)) { # Boxplot name cat(paste('% ', bp$names[c], '\n', sep=''))
# Boxplot command
# Options for each boxplot
for (o in options) {
cat(paste('\t', o, ',\n', sep=''))
}
# Boxplot prepared quantities
cat('\tboxplot prepared={%\n')
cat(paste('\t\tlower whisker  = ', bp$stats[1,c], ',\n', sep='')) cat(paste('\t\tlower quartile = ', bp$stats[2,c], ',\n', sep=''))
cat(paste('\t\tmedian         = ', bp$stats[3,c], ',\n', sep='')) cat(paste('\t\tupper quartile = ', bp$stats[4,c], ',\n', sep=''))
cat(paste('\t\tupper whisker  = ', bp$stats[5,c], ',\n', sep='')) cat(paste('\t\tsample size = ', bp$n[c], ',\n', sep=''))
cat('\t},\n')
# Outliers
out <- bp$out[bp$group==c]
if (length(out) == 0) {
cat('] coordinates {};\n')
} else {
cat('] table[y index=0, meta=id, row sep=\\\\] {\n')
cat('\tx id \\\\\n')
for (o in 1:length(out)) {
cat(paste('\t', out[o], ' ', o, ' \\\\\n', sep=''))
}
cat('};\n')
}
}
}


In R, you can then save the boxplot object and pass it as an argument to pgfbp:

boxplot(data$response ~ data$group) -> bp
pgfbp(bp)


and copy the output to your tex file.

# Labeling outliers

As for the meta column, the reason I included it in this function is because sometimes (particularly when showing initial plots to my supervisor) it is useful to label the outliers to be able to identify unusual tendencies in a single participant. This I do together with a pgfplots style:

\pgfplotsset{
label outliers/.style={
mark size=0,
nodes near coords,
every node near coord/.style={
font=\tiny,
anchor=center
},
point meta=explicit symbolic,
},
}


but I still have to find a good solution for extracting the labels for each outlier from the data (I have a kludge put together from a previous version, but I thought this was a bit too specific for this question). The version above uses numbers as placeholders, but they are easy to remove if they are not used.

-

Without pgfplots you can insert chunks of R code directly in the text file and obtain the results of this chunks (text, tables or figures) instead of the R code in the PDF file.

The source file must have the extension .Rnw (R noweb) that R with the Sweave fuction (or knitr) convert in a normal .tex that you compile as usual. If you use rstudio the editor can make all the steps for you with one click.

% File example.Rnw
% compile with:
% R CMD Sweave example.Rnw
% pdflatex example.tex
\documentclass{article}
\begin{document}
\SweaveOpts{concordance=TRUE}
\begin{figure}[h!]
\centering
<<echo=F,fig=T>>=
a <- c(1,23,42,13,33,56,23,45,87)
boxplot(a, col="cyan")
@
\caption{This is R boxplot in a \LaTeX\ file}
\end{figure}
\end{document}

-