Floating figures creating breaks in code chunks in PDF

I have been using the default setting for figure floating according to the R Markdown Cookbook (6.5 Control the placement of figures | R Markdown Cookbook) but sometimes figures float forward to the top of the next page creating a break in a code chunk which makes the whole thing hard to read - especially since the figure that floated was from one example, and lands in the middle of the next example.

I have added the lines:

\usepackage{float}
\floatplacement{figure}{H}

to my preample.tex, but as predicted in section 6.5.2, this stops figures from floating at all and is not exactly right either.

All I really want is for code chunks to not be broken by figures - being broken by page breaks seems OK, but when a figure floats to the top of a page the break seems really off.

Looking at the various posts on this, figure floating seems to be a real sticking point, but I haven't found any answers related to the special nature of code chunks.

Any suggestions on how to prevent code chunks from being split by floating figures?

You have difficulties placing the figures.
Is it an idea placing the code chunks by manually inserting \newpage statements before starting a code chunk?
Or splitting long code chunks in two or more smaller ones that maybe can be placed on pages in an easier way?
I am aware that this is not the automated way you are probably looking for.

A small example with the type of code and plots you are considering could be helpful for forum readers.

2 Likes

I'm trying not to go too crazy with this since I'm not done writing and I'm not sure where things will be at the end. But two things seemed to help:

The suggestion to put the \newpage statement right before the code chunk moved the entire chunk below the floated figure which is perfect! Problem basically solved. I also tried the settings from the R Markdown Cookbook:

\renewcommand{\topfraction}{.85}
\renewcommand{\bottomfraction}{.7}
\renewcommand{\textfraction}{.15}
\renewcommand{\floatpagefraction}{.66}
\setcounter{topnumber}{3}
\setcounter{bottomnumber}{3}
\setcounter{totalnumber}{4}

Which also did a much better job of floating the figures in general. I think between the new settings and the ability to place specific code chunks when things get weird, I'll get a PDF that I can work with.

I want to keep working in R Markdown rather than switching to LaTex. Sprinkling a few commands into the .Rmd file is a good solution for me.

Thanks for the help!

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.