stop_floating_in_latex: How to stop figures from floating away in LaTeX

stop_floating_in_latexR Documentation

How to stop figures from floating away in LaTeX

Description

This isn't a function—it's just a note to document something that I found to be very useful.

When I convert R Markdown files to LaTeX via knitr, I end up putting \\FloatBarrier after every figure so it doesn't float past where I want it in the document. Using knitr's hooks, I can make this process happen automatically.

In order to do that, you first need to include the LaTeX package placeins (i.e., via header-includes: \\usepackage{placeins}). Then, in the first chunk, you should put the function:

knitr::knit_hooks$set(plot = function (x, options) {
  float_correct <- function(f, y, opts)  {
    if (is.null(opts$regfloat) || opts$regfloat==FALSE)
      paste0(f(y, opts), "\n\n\\\\FloatBarrier\n")
    else
      f(y, opts)
  }
  if (!is.null(options$out.width) || !is.null(options$out.height) ||
      !is.null(options$out.extra) || options$fig.align != "default" ||
      !is.null(options$fig.subcap)) {
    if (is.null(options$fig.scap))
      options$fig.scap = NA
    return(float_correct(knitr:::hook_plot_tex, x, options))
  }
  return(float_correct(knitr:::hook_plot_md_base, x, options))
})

In order to disable this behavior for specific chunks, just put regFloat=TRUE as a chunk option.


burchill/zplyr documentation built on Feb. 2, 2023, 11:01 a.m.