baptiste baptiste - 29 days ago 17
R Question

figure* environment in twocolumn knitr/Sweave document

Sounds like it should be a common problem, but I didn't find an obvious trick.
Consider the knitr Rnw file below,

\documentclass[twocolumn, 12pt]{article}
\usepackage{graphicx}
\begin{document}
%\SweaveOpts{dev=pdf, fig.align=center}
\begin{figure*}
<<aaa, fig.width=8, fig.height=5, fig.show=hold>>=
plot(1,1)
@
\end{figure*}
\end{document}


I would like this wide figure to span two columns, using a
{figure*}
LaTeX environment. Is there a hook for that?

EDIT: wrapping the chunk in
figure*
gives the following output.

enter image description here

Answer

Two facts:

  1. knitr makes everything accessible for you, so LaTeX tricks are often unnecessary;
  2. there is a chunk hook with which you can wrap your chunk results;

A simple-minded solutions is:

knit_hooks$set(chunk = function(x, options) {
                       sprintf('\\begin{figure*}\n%s\n\\end{figure*}', x)
})

I leave the rest of work to you to take care of more details in options (e.g. when options$fig.keep == 'none', you should not wrap the output in figure*). You may want to see how the default chunk hook for LaTeX is defined in knitr to know better how the chunk hook works.

However, in this case, I tend to write the LaTeX code by myself in the document instead of automatically creating it. After you have got figure*, you may start to think about \caption{} and \label{} (not hard, but I still want to see them in LaTeX).