How do I remove empty space between code chunks in Rmd output to PDF?

Viewed 1594

How do I remove the extra empty space between the end of a chart and the next one? I have a shiny app that runs a parameterized .Rmd that outputs to both html and PDF. The html is fine, but there is too much white space in the PDF. I am supposed to fit everything in two pages (hence the squishy margins/geometry), but the text I need to add at the bottom of page 1 doesn't fit AND inserts a blank first page. There is space between my charts, and if I could remove it, everything would probably fit. (The layout is done in a table for html (as I have too much going on to figure out how to do that in css) and is done in multi-columns layout in LaTeX (pilfered code from here and then by looking at the .tex my code made so far).

I don't know LaTeX (I have spent weeks cobbling together what I have so far). I have made an example below, as I cannot share my data. Hopefully it is enough, but not too much!

My YAML:

---
params:
  Country: Canada
geometry: "left=1cm,right=1cm,top=1.5cm,bottom=2cm"
header-includes:
- \usepackage{booktabs}
- \usepackage{longtable}
- \usepackage{array}
- \usepackage{multirow}
- \usepackage{wrapfig}
- \usepackage{float}
- \usepackage{colortbl}
- \usepackage{pdflscape}
- \usepackage{tabu}
- \usepackage{threeparttable}
- \usepackage{threeparttablex}
- \usepackage[normalem]{ulem}
- \usepackage{makecell}
- \usepackage{fancyhdr}
output:
  pdf_document: 
    keep_tex:  true
    includes:
      in_header: www\columns.tex
  html_document: default
pagetitle: Fact Sheets
---

knitr::opts_chunk$set(echo = FALSE)

## need "html" so that formatting shows up (see colorize function)
options(knitr.table.format = function() {
  if (knitr::is_latex_output()) "latex" else "html"
})

## https://bookdown.org/yihui/rmarkdown-cookbook/font-color.html
colorize <- function(x, color) {
  if (knitr::is_latex_output()) {
    ## trick it into using color='blue' instead of a hexcode with # that breaks the LaTeX code
    sprintf("\\textcolor[HTML]{2A64AB}{%s}", x)
  } else if (knitr::is_html_output()) {
    sprintf("<span style = 'color: %s;'>%s</span>", color, x)
  } else x
}

text1 <- paste(words[1:200], collapse = " ")
text2 <- paste(words[1:200], collapse = " ")

Then, I make a bunch of kbls with kable_styling, charts, dynamic titles and text. I also have a chunk to make a LaTeX environment (??) but I have commented it out as the PDF is made regardless, and the code actually shows \begin{tiny} in PDF. (There is a corresponding close chunk at the end of my file, also commented out.)

## The LaTeX environment `tiny` is only generated for LaTeX output.
# knitr::asis_output('\n\n\\begin{tiny}')

I add a latex chunk to set a fancy header and footer, and begin the multi-column layout.

\pagestyle{fancy}
\setlength\headheight{29pt}
\fancyhead[L]{\fontsize{20}{22} \selectfont {\textbf{Fact Sheet}}}
\fancyhead[R]{\fontsize{20}{22} \selectfont {\textbf{`r colorize(toupper(params$Country), color = '#2A64AB')`}}}
\fancyfoot[L]{My Left Footer}
\fancyfoot[C]{My Center Footer}
\fancyfoot[R]{My Right Footer}
\renewcommand{\headrule}{\vbox to 0pt{\hbox to\headwidth{\dotfill}\vss}}

\begin{cols}
\begin{col}{0.52\textwidth}

Then I have a latex-output-only chunk:

format.for.pdf <- function(tab, alignVector, boldRow) {
  tab %>% 
    kbl(align = {{alignVector}}, booktabs = TRUE, linesep = "") %>%
    kable_styling(full_width = F, position = "left", font_size = 6.4, latex_options = "striped") %>%
    column_spec(1, width = "25em") %>%
    column_spec(2:3, width = "4em") %>%
    row_spec(0, color = "#2A64AB") %>%
    row_spec(boldRow, bold = TRUE)
}
## PDF-only code
format.for.pdf(tab = mtcars[1:9, 1:5], alignVector = c("l", "c", "c", "c", "c"), boldRow = 0)
format.for.pdf(tab = mtcars[10:19, 1:5], alignVector = c("l", "c", "c", "c", "c"), boldRow = 9)
format.for.pdf(tab = mtcars[20:32, 1:5], alignVector = c("l", "c", "c", "c", "c"), boldRow = 4)
format.for.pdf(tab = mtcars[1:6, 6:11], alignVector = c("l", "c", "c", "c", "c"), boldRow = 3)
format.for.pdf(tab = mtcars[7:14, 6:11], alignVector = c("l", "c", "c", "c", "c"), boldRow = 1)

I add some latex code to end column one, add a tiny middle column to add whitespace (ironically), and start right-side column.

\end{col}
\begin{col}{0.02\textwidth}

~

\end{col}
\begin{col}{0.46\textwidth}

I add some html code to start a table layout for html version.

<table>
  <tr>
    <td width = "52%">
      <h1><strong>Fact Sheet</strong></h1></br>

Run chunk with option include = knitr::is_html_output()

## html-only code
mtcars[1:9, 1:5]
mtcars[10:19, 1:5]
mtcars[20:32, 1:5]
mtcars[1:6, 6:11]
mtcars[7:14, 6:11]

Html code to close left "column", add white-spaced middle "column" and begin right-side "column".

</td>
<td width = "2%">&nbsp;&nbsp;</td>
<td width = "46%", valign = "top">
  <h1><strong><center>`r colorize(toupper(params$Country), color = '#2A64AB')`</center></strong></h1></br>

THIS IS WHERE THERE IS TOO MUCH WHITE SPACE (just one line, but I'd like it gone).
chart title here

ggplot2::ggplot(mtcars, mapping = aes(x = cyl)) +
    geom_bar()

AND AGAIN HERE
another chart title here

ggplot2::ggplot(mtcars, mapping = aes(x = mpg)) +
    geom_dotplot()

AND AGAIN HERE
third chart title here

ggplot2::ggplot(mtcars, mapping = aes(x = mpg, y = cyl)) +
    geom_line()

I add some latex code to shrink text size to match tables better and to save space.

\fontsize{8}{10}\selectfont

HERE IS ANOTHER LINE OF WHITE SPACE

**`r colorize(text1_title, color = "#2A64AB")`**
`r text1`

**`r colorize(text2_title, color = "#2A64AB")`**   
`r text2`

Latex code to close multi-columns

\end{col}
\end{cols}

Html code to close table tags

    </td>
  </tr>
</table>

(and then my page 2 stuff which isn't needed to reproduce issue)

too  much white space

My sessionInfo():

R version 3.6.0 (2019-04-26)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 18363)

Matrix products: default

locale:
[1] LC_COLLATE=English_Canada.1252  LC_CTYPE=English_Canada.1252    LC_MONETARY=English_Canada.1252
[4] LC_NUMERIC=C                    LC_TIME=English_Canada.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
 [1] kableExtra_1.2.1      janitor_2.0.1         openxlsx_4.2.2        forcats_0.5.0        
 [5] stringr_1.4.0         dplyr_1.0.2           purrr_0.3.4           readr_1.3.1          
 [9] tibble_3.0.3          tidyverse_1.3.0       tidyr_1.1.2           markdown_1.1         
[13] shinycssloaders_1.0.0 shinyjs_2.0.0         plotly_4.9.2.1        ggplot2_3.3.2        
[17] shinydashboard_0.7.1  shinythemes_1.1.2     htmlwidgets_1.5.1     DT_0.15              
[21] lubridate_1.7.9       shiny_1.5.0          

loaded via a namespace (and not attached):
 [1] matrixStats_0.56.0   fs_1.5.0             webshot_0.5.2        httr_1.4.2           rstan_2.21.2        
 [6] tools_3.6.0          backports_1.1.10     utf8_1.1.4           R6_2.4.1             DBI_1.1.0           
[11] lazyeval_0.2.2       colorspace_1.4-1     withr_2.3.0          tidyselect_1.1.0     gridExtra_2.3       
[16] prettyunits_1.1.1    processx_3.4.4       curl_4.3             compiler_3.6.0       cli_2.0.2           
[21] rvest_0.3.6          xml2_1.3.2           scales_1.1.1         callr_3.4.4          digest_0.6.25       
[26] StanHeaders_2.21.0-6 rmarkdown_2.3        pkgconfig_2.0.3      htmltools_0.5.0      highr_0.8           
[31] dbplyr_1.4.4         fastmap_1.0.1        rlang_0.4.7          readxl_1.3.1         rstudioapi_0.11     
[36] farver_2.0.3         generics_0.0.2       jsonlite_1.7.1       crosstalk_1.1.0.1    zip_2.1.1           
[41] inline_0.3.16        magrittr_1.5         loo_2.3.1            Rcpp_1.0.5           munsell_0.5.0       
[46] fansi_0.4.1          lifecycle_0.2.0      yaml_2.2.1           stringi_1.5.3        snakecase_0.11.0    
[51] pkgbuild_1.1.0       plyr_1.8.6           grid_3.6.0           blob_1.2.1           parallel_3.6.0      
[56] promises_1.1.1       crayon_1.3.4         haven_2.3.1          hms_0.5.3            knitr_1.30          
[61] ps_1.3.4             pillar_1.4.6         codetools_0.2-16     stats4_3.6.0         reprex_0.3.0        
[66] glue_1.4.2           evaluate_0.14        packrat_0.5.0        V8_3.2.0             data.table_1.13.0   
[71] RcppParallel_5.0.2   modelr_0.1.8         png_0.1-7            vctrs_0.3.4          httpuv_1.5.4        
[76] cellranger_1.1.0     gtable_0.3.0         assertthat_0.2.1     xfun_0.17            mime_0.9            
[81] xtable_1.8-4         broom_0.7.0          later_1.1.0.1        rsconnect_0.8.16     viridisLite_0.3.0   
[86] tinytex_0.26         ellipsis_0.3.1      
0 Answers
Related