سؤال

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

هل كانت مفيدة؟

المحلول

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

نصائح أخرى

Not sure about how knitr but for Sweave (and basic latex) there is in fact a trick: have the R code produce a pdf file, and then use standard \includegraphics to pull it in.

So with this:

\documentclass[twocolumn, 12pt]{article}
\usepackage{graphicx}
\begin{document}
%\SweaveOpts{dev=pdf}

<<aaa,fig=FALSE,print=FALSE,echo=FALSE>>=
pdf("mychart.pdf", width=6, height=3)
set.seed(42)
plot(cumsum(rnorm(100)), type='l', main="yet another random walk")
invisible(dev.off())
@

\begin{figure*}
  \includegraphics{mychart.pdf}
\end{figure*}

\end{document}

I got the document below (which I then converted from pdf to png):

enter image description here

I also had a similar problem while preparing a figure that should span two columns in a IEEE two-column conference paper.

Setting the chunk hook caused some strange error in my setup. Even this simple hook: knit_hooks$set(chunk = function(x, options) x)

But after looking into knitr::opts_chunk$get(), I realized that simply setting fig.env="figure*" solves the problem in an elegant way.

Here is how my chunk looks like in an Rnw file:

<<fig1, fig.width=18, fig.height=6, fig.env="figure*">>=
@
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top