Figure * environment in twocolumn knitr / Sweave document

It seems like this should be a common problem, but I did not find an explicit 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 the {figure*} LaTeX environment. Is there a hook for this?

EDIT: The block wrapper in figure* gives the following output.

enter image description here

+4
source share
3 answers

Two facts:

  • knitr makes everything available to you, so LaTeX tricks are often not needed;
  • there is a chunk hook with which you can wrap the results of your piece;

Simple ideas:

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

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

However, in this case, I try to write LaTeX code myself in the document, and not automatically create it. After you get figure* , you can start thinking about \caption{} and \label{} ( not difficult , but I still want to see them in LaTeX).

+6
source

I donโ€™t know how to knitr, but for Sweave (and base latex) there is actually a trick: ask the R-code to create a pdf file, and then use the 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 then converted from pdf to png):

enter image description here

+2
source

I also had a similar issue when preparing a shape that should span two columns in an IEEE two-column conference.

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

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

Here's what my piece in the Rnw file looks like:

 <<fig1, fig.width=18, fig.height=6, fig.env="figure*">>= @ 
0
source

Source: https://habr.com/ru/post/1392573/


All Articles