R Markdown - Positioning table and plot side by side - r-markdown

I am using R Markdown to output to pdf, and I am trying to get a table and a plot aligned side by side horizontally. I can get fig.align = "right" to align the plot to the right of the page, but it is plotted under the table (formatted with kable) and not side by side with it. Any tips?

Here is a way using the TeX package floatrow:
---
title: "Untitled"
header-includes:
- \usepackage{floatrow}
output:
pdf_document:
keep_tex: true
---
\newfloatcommand{btabbox}{table}
\begin{figure}[H]
\begin{floatrow}
\ffigbox{%
```{r, fig.align = "right", echo = F}
plot(mpg ~ hp, data = mtcars)
```
}{\caption{A figure}}
\btabbox{%
```{r, fig.align = "right", echo = F}
knitr::kable(head(mtcars[,1:3]), format = "latex")
```
}{\caption{A table}}
\end{floatrow}
\end{figure}

I prefer the method by Martin, but if you wanted to have a less LaTeX reliant solution, you could convert the table into a grid graphic and plot it as a subfigure:
---
header-includes:
- \usepackage{subfig}
output: pdf_document
---
```{r, fig.cap='two plots', fig.subcap= c('A figure', 'A table'), out.width = '.49\\linewidth', echo = F, fig.align='center'}
library(gridExtra)
library(grid)
plot(mpg ~ hp, data = mtcars)
grid.newpage()
grid.table(head(mtcars[,1:6]), theme = ttheme_minimal())
```

I was able to do this with a combination of the multicol package and minipages. Just another option...
Here's the code:
---
title: "Untitled"
header-includes:
- \usepackage{multicol}
- \newcommand{\btwocol}{\begin{multicols}{2}}
- \newcommand{\etwocol}{\end{multicols}}
output:
pdf_document:
keep_tex: true
---
```{r minipage_funs, echo = FALSE}
## adding minipages in Rmarkdown only seems to work for me when returned from function
fig_table_mp_start <- function() {
return("\\begin{minipage}{\\textwidth}")
}
fig_table_mp_end <- function() {
return("\\end{minipage}")
}
```
`r fig_table_mp_start()`
\btwocol
```{r, fig.align = "right", echo = FALSE}
plot(mpg ~ hp, data = mtcars)
```
```{r, fig.align = "right", echo = FALSE}
knitr::kable(head(mtcars[,1:3]), format = "latex")
```
\etwocol
`r fig_table_mp_end()`
I assume you can play around with padding to make it look pretty.

Related

using a for loop to generate a series of plots in new powerpoint slides using quarto

I am creating a quarto powerpoint presentation and want to use a dataset to iterate over all the classes in a variable and do a plot for each class on a new slide. However, my plot doesn't seem to show up
---
title: "test_quarto_presentation"
format: pptx
editor: visual
---
## Quarto
Trying to iterate over each species and print the distributions on slides
```{r}
library(tidyverse)
```
```{r, results='asis'}
for (species in unique(iris$Species)){
cat(paste0('## ', species))
print("test")
print(iris %>%
filter(Species == "virginica") %>%
ggplot(aes(x = Petal.Length)) +
geom_histogram())}
```
Here is an option by producing the plots beforehand using purrr based on this discussion:
---
title: "test_quarto_presentation"
format: pptx
---
```{r, include=FALSE}
library(tidyverse)
spec_name <- unique(iris$Species)
make_hist <- function(spec) {
iris |>
filter(Species == spec) |>
ggplot(aes(x = Petal.Length)) +
geom_histogram()
}
list_hist <- map(spec_name, make_hist)
df <- tibble(spec = spec_name, plots = list_hist)
```
```{r}
#| output: asis
res <- pmap_chr(df, \(spec, plots) {
knitr::knit_child(text = c(
"## `r spec`",
"```{r}",
"#| echo: false",
"plots",
"```",
""), envir = environment(), quiet = TRUE)
})
cat(res, sep = '\n')
```
Output:

rmarkdown does not render PDFs as batch

No solution offered yet and cross-posted to RStudio community:
https://community.rstudio.com/t/rmarkdown-does-not-render-pdfs-as-batch/136316
I have a rmarkdown file that renders well in RStudio with the Knitr button or with rmarkdown() but does not render when rendered as part of a batch with purrr::walk() and being passed a parameter. The batch issue only occurs when fig.show="hold", out.width="50%" is included in a section of the rmarkdown file.
library(purrr)
library(tinytex)
SurveySet <- c(20,19,68,79,30,18,42)
purrr::walk(
.x = SurveySet,
~ rmarkdown::render(
input = "Test.Rmd",
output_file = glue::glue("REPORTS/Report Fails {.x}.pdf"),
params = list(Unit = {.x})
)
)
purrr::walk(
.x = SurveySet,
~ rmarkdown::render(
input = "TestWorks.Rmd",
output_file = glue::glue("REPORTS/Report Works {.x}.pdf"),
params = list(Unit = {.x})
)
)
Test.Rmd as
---
title: "`r params$Unit`"
output: pdf_document
params:
Unit: 68
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
## R Markdown
This Document renders with RStudio Knitr button but not with batch
```{r figures-side, fig.show="hold", out.width="50%"}
par(mar = c(4, 4, .1, .1))
plot(cars)
plot(mpg ~ hp, data = mtcars, pch = 19)
```
TestWorks.Rmd as
---
title: "`r params$Unit`"
output: pdf_document
params:
Unit: 68
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
## R Markdown
Without fig.show="hold", out.width="50%" this document renders individually and as batch
```{r figures}
par(mar = c(4, 4, .1, .1))
plot(cars)
plot(mpg ~ hp, data = mtcars, pch = 19)
```

How to remove white padding/borders that tint::tintHtml added around cells in kable table?

I'd like to get rid of the white around each cells. When I knit to html_document there is no such padding.
I'm guessing the tint.css file is responsible for this (https://github.com/eddelbuettel/tint/blob/master/inst/rmarkdown/templates/tintHtml/resources/tint.css)
---
title: tintHtml() add padding to kable "
output: tint::tintHtml
---
```{r}
library(kableExtra)
library(magrittr)
```
```{r}
knitr::kable(
mtcars[1:6, 1:6],
caption = 'how do I get rid of white padding ?'
) %>%
row_spec(0, background = "blue", color = "white") %>%
row_spec(1, background = "green", color = "white")
```
Step one: You may "right-click an element on a web page and select Inspect Element"
Step two: You will need to override the default border-spacing (Bootstrap CSS) property:
The border-spacing property sets the distance between the borders of
adjacent cells.
Note: This property works only when border-collapse is
separate.
<style>
table{
border-spacing: unset; # values: inherent, initial, unset or 0px
}
</style>
Output:
---
title: tintHtml() add padding to kable "
output: tint::tintHtml
---
```{r}
library(kableExtra)
library(magrittr)
```
<style>
table{
border-spacing: unset; # inherent, initial, unset, 0px
}
</style>
```{r}
knitr::kable(
mtcars[1:6, 1:6],
caption = 'how do I get rid of white padding ?'
) %>%
row_spec(0, background = "blue", color = "white") %>%
row_spec(1, background = "green", color = "white")
```

How do you filter a data frame in a shiny document and display a datatable?

I'm trying to filter a data frame and then do some simple ggplots off of the data. I've tried to leverage the R studio example on Shiny documents along with the following SO post on the subject:
Reactively filtering/subsetting a data frame in shiny
Here is my code.
---
title: "Shiny Filter Test"
author: "Novice"
date: "12/13/2019"
output: html_document
runtime: shiny
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r}
library(tidyverse)
library(shiny)
inputPanel(
selectInput("n_break", label = "Number of bins:",
choices = c(10, 20, 35, 50), selected = 10)
)
cdat <- reactive({
data <- tibble(x = c(10,20,35), y = c("a","b","c"))
data %>%
filter(x %in% input$n_break)
output$table <- DT::renderDT({
cdat()
}, options = list(scrollX = TRUE))
})
```
Can anyone point out where I'm going wrong? When I run the code I get my dropdown box, but that is all. No errors. Just no filtered datatable.
Thanks.
The closing brackets of your reactive are at the wrong place. They should close once you have filtered the data.
---
title: "Shiny Filter Test"
author: "Novice"
date: "12/13/2019"
output: html_document
runtime: shiny
---
```{r setup}
knitr::opts_chunk$set(
echo = FALSE
)
```
```{r}
library(tidyverse)
library(shiny)
inputPanel(
selectInput("n_break", label = "Number of bins:",
choices = c(10, 20, 35, 50), selected = 10)
)
cdat <- reactive({
data <- tibble(x = c(10,20,35), y = c("a","b","c"))
data %>% filter(x %in% input$n_break)
})
DT::renderDT({
cdat()
}, options = list(scrollX = is ))
```
A remark on the reactive: if you plan to extend this futher, such that the filtered data is used elsewhere, it makes sense to do the filtering in a reactive function. However, if this is not the case I would just do the filtering inside the renderDT:
---
title: "Shiny Filter Test"
author: "Novice"
date: "12/13/2019"
output: html_document
runtime: shiny
---
```{r setup}
knitr::opts_chunk$set(
echo = FALSE
)
```
```{r}
library(tidyverse)
library(shiny)
data <- tibble(x = c(10,20,35), y = c("a","b","c"))
inputPanel(
selectInput("n_break", label = "Number of bins:",
choices = c(10, 20, 35, 50), selected = 10)
)
DT::renderDT({
data %>% filter(x %in% input$n_break)
}, options = list(scrollX = TRUE))
```

Xtable grey rows overwritting vertical lines

---
title: "Title"
author: ''
date: ''
output:
pdf_document:
template: default.tex
geometry: top=0.5cm, bottom=0.5cm, left=0.5cm, right=0.5cm
header-includes: null
fontsize: 4pt
classoption: portrait
sansfont: Calibri Light
---
#Name1: `r "Name1"`
#Name2: `r "Name2"`
```{r, echo=FALSE, message=FALSE, warning=FALSE, results='asis'}
df <- mtcars
n = nrow(df)
hlines=c(-1,0,(n-1),n)
my_align = "c|c|c|ccccc|ccc|c|"
rws <- seq(1, (n-1), by = 2)
col <- rep("\\rowcolor[gray]{.90} ", length(rws))
xtable::print.xtable(xtable(df
, align = my_align)
, add.to.row = list(pos = as.list(rws), command = col)
, booktabs = F
, hline.after = hlines, type = "latex")
```
I am using an Rmarkdown to print a table which has a lot of formatting. When I add the add.to.rwo part to get grey and white alternate rows the vertical lines are removed in the grey rows.
How do I correct this? It is very difficult to create a reproducible example but hopefully the same problem will apply to any df (with the correct Latex packages behind it)
Thanks :)
Try comparing these two tables. The first is your table as you coded it, the second is done by pixiedust with the hhline option set to TRUE.
---
title: "Title"
author: ''
date: ''
output:
pdf_document:
geometry: top=0.5cm, bottom=0.5cm, left=0.5cm, right=0.5cm
header-includes:
- \usepackage{amssymb}
- \usepackage{arydshln}
- \usepackage{caption}
- \usepackage{graphicx}
- \usepackage{hhline}
- \usepackage{longtable}
- \usepackage{multirow}
- \usepackage[dvipsnames,table]{xcolor}
fontsize: 4pt
classoption: portrait
sansfont: Calibri Light
---
#Name1: `r "Name1"`
#Name2: `r "Name2"`
```{r, echo=FALSE, message=FALSE, warning=FALSE, results='asis'}
library(xtable)
df <- mtcars
n = nrow(df)
hlines=c(-1,0,(n-1),n)
my_align = "c|c|c|ccccc|ccc|c|"
rws <- seq(1, (n-1), by = 2)
col <- rep("\\rowcolor[gray]{.90} ", length(rws))
xtable::print.xtable(xtable(df
, align = my_align)
, add.to.row = list(pos = as.list(rws), command = col)
, booktabs = F
, hline.after = hlines, type = "latex")
```
```{r}
library(pixiedust)
dust(df,
hhline = TRUE,
keep_rownames = TRUE) %>%
medley_bw() %>%
sprinkle_colnames(.rownames = "") %>%
sprinkle(cols = c(".rownames", "mpg", "cyl", "qsec", "gear", "carb"),
border = "right") %>%
sprinkle(rows = nrow(mtcars),
border = "top") %>%
sprinkle(bg_pattern_by = "rows")
```