Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

figure* environment in twocolumn knitr/Sweave document

Tags:

r

knitr

tex

sweave

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

like image 832
baptiste Avatar asked Jan 23 '12 23:01

baptiste


1 Answers

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).

like image 72
Yihui Xie Avatar answered Sep 24 '22 16:09

Yihui Xie