How to make sparklines in R Rmd to pdf?

858 views Asked by At

in my Rmd to pdf, I want to have sparklines in a table. For an example that works in Rmd to html, look at https://stackoverflow.com/a/54578219/6170807. The build-in histograms and boxplots in kableExtra work fine in Rmd to pdf, but I want to have a line graph, not a histogram or boxplot. Anyone a suggestion? Thanks!

1

There are 1 answers

0
Martin Schmelzer On BEST ANSWER

Here is a basic example. We simply create a plot for each row/group and save it. In the table we add the latex code to the corresponding plot. Its up to you how to style and format the plots. You could check the source code of kableExtra to learn from how histograms and boxplots are implemented.

Another option would be to use pagedown to render paged HTML reports and print them using pagedown::chrome_print or manually through your browser. That way you can use the HTML sparkline approach.

---
output: pdf_document
---

```{r, include=F}
library(tidyverse)
library(ggplot2)
library(tidyr)
library(scales)

df <- data.frame(Country = rep(c("A", "B", "C"), 5), 
                 Year = c(rep(2000, 3), rep(2001, 3), rep(2002, 3), rep(2003, 3), rep(2004, 3)),
                 Value = sample(1000:2000, size = 15))



df %>%
  group_by(Country) %>%
  do({
    p <- ggplot(., aes(x = Year, y = Value)) + 
      geom_line(size = 5, color = ifelse(tail(.$Value, n = 1) < head(.$Value, n = 1), "firebrick3", "springgreen")) + 
      geom_line(size = 2.5, color = ifelse(tail(.$Value, n = 1) < head(.$Value, n = 1), "firebrick", "springgreen3")) + 
      theme_void()
    ggsave(p, filename = paste0("fig", unique(.$Country), ".pdf"), width = 4, height = 1.25)
    invisible(.)
  })


df <- df %>%
  pivot_wider(names_from = Year, values_from = Value) %>%
  mutate(Sparkline = paste0("\\raisebox{-.5\\height}{\\includegraphics[width=2cm]{fig", Country, ".pdf}}"))
```

```{r, echo  = F}
knitr::kable(df, escape = F)
```

enter image description here