RMarkdown生成LaTeX/PDF时,浮动图导致段落间空白问题咨询
Let's start with why this happens: RMarkdown's default PDF output uses LaTeX with a non-zero \parskip (vertical space between paragraphs) to separate text blocks instead of relying on indentation. When LaTeX moves your floating figure to a "suitable position", it leaves behind that paragraph spacing between your two text blocks—something that doesn't occur in pure LaTeX if you structure your float without extra paragraph breaks.
Here are three practical solutions to resolve this:
1. Force the Figure to Stay in Place (Disable Floating)
If you don't need the figure to float and want it to appear exactly where you placed it in the Rmd, use the float LaTeX package to lock the position with fig.pos='H':
--- output: pdf_document: extra_dependencies: float --- This is my first paragraph. Next in the Rmd file would be the code for the figure. The figure is correctly treated as a float by LaTeX, meaning that LaTeX will put it to the next suitable position. ```{r pressure, echo=FALSE, fig.cap="Example", out.width='0.5\\textwidth', fig.pos='H'} plot(pressure)
The problem now is, that this leaves space to my second paragraph. Usually, this should not be the case. In pure LaTeX, there is a linebreak, of course, but no vertical space in addition.
## 2. Offset the Extra Space (Keep Floating Behavior) If you want to retain the figure's floating ability but eliminate the unwanted gap, use LaTeX's `\vspace` command to cancel out the default paragraph spacing before and after the code block:
output: pdf_document
This is my first paragraph.
Next in the Rmd file would be the code for the figure. The figure is correctly treated as a float by LaTeX, meaning that LaTeX will put it to the next suitable position.
\vspace{-\parskip}
plot(pressure)
\vspace{-\parskip}
The problem now is, that this leaves space to my second paragraph. Usually, this should not be the case. In pure LaTeX, there is a linebreak, of course, but no vertical space in addition.
`\parskip` refers to the exact vertical space LaTeX adds between paragraphs, so using a negative value cancels out the extra gap. ## 3. Global Adjustment: Match Pure LaTeX's Paragraph Style If you want your entire document to behave like pure LaTeX (using indentation instead of vertical space between paragraphs), set `\parskip` to 0 and enable paragraph indentation at the top of your Rmd:
output: pdf_document
\setlength{\parskip}{0pt}
\setlength{\parindent}{1em}
This is my first paragraph.
Next in the Rmd file would be the code for the figure. The figure is correctly treated as a float by LaTeX, meaning that LaTeX will put it to the next suitable position.
plot(pressure)
The problem now is, that this leaves space to my second paragraph. Usually, this should not be the case. In pure LaTeX, there is a linebreak, of course, but no vertical space in addition.
内容的提问来源于stack exchange,提问作者NicolasBourbaki

