How to control placement of tables and plots in rmarkdown for PDF output?

Viewed 48

I have read what feels like 100 articles and threads on the topic and tried so many things I have lost count of it all but am still stuck. I have managed to make some minor improvements but still not all tables and plots are being placed where I am intending them to be.

Please let me know if I need to add more or less code and output examples to make this question better.

Essentially what I am trying to achieve is:

  1. A line of text explaining the table or plot
  2. Underneath it, the relevant table or plot
  3. Rinse and repeat

In the YAML code and first chunk I have this:

---
    date: "`r format(Sys.time(), '%d %B, %Y')`"
output:
  pdf_document:
    latex_engine: pdflatex
    keep_tex: yes
    extra_dependencies: flafter
header-includes: \usepackage{float}
---
```{r, echo=FALSE}
knitr::opts_chunk$set(fig.pos = 'H')
```

Following this I have the code to produce the table (which I have not included) and then I place the text followed by a chunk to render the table:

This is the table of numerical summaries for demand by state.

```{r, echo=FALSE, warning=FALSE,message=FALSE, fig.pos="H"}
kbl(daily_num_sumaries, caption = "Electricity Demand: Numerical Summaries", booktabs = T) %>%
kable_styling(font_size = 12, latex_options = c("striped", "scale_down"))
```

Then I have a chunk to produce the plot (which I have not included), followed by text to discuss the plot and the a chunk to render the plot:

This is a boxplot.

```{r demand_boxplot, echo=FALSE, fig.pos="H"}
plot(demand_boxplot)
```

I repeat this multiple times however you'll note on the PDF output that it is not rendering to the PDF in this order. Can anyone see where I am going wrong?

PDF_Output

Thanks in advance!

EDIT

With a sample df:

start_date <- as.Date("2020/01/01") 

df <- data.frame(
  REGION = rep(c("NSW", "VIC", "QLD", "SA", "TAS"), each=50),
  DATE = seq(start_date, by = "day", length.out = 250),
  DAILY_COST = runif(250, min=0, max=743884569),
  DAILY_DEMAND = runif(250, min = 0, max = 337297)
)
0 Answers
Related