3

I am using Rmarkdown to automate generating a bunch of plots. I have code like:

```{r make_plots}
for (a_ggplot in a_bunch_of_ggplots()) {
    print(a_ggplot)
}
```

I'd like to make the plots different heights. Normally I'd set the height with fig.height in the chunk header. I tried using a vector for fig.height without success. (I think it just used the last value.)

How do I make the plots different heights?

Also, I'll want to add some document headers. I'm planning on trying technique from this answer (generating raw markdown and using results='asis'). Bonus points if your solution is compatible with it!

EDIT: Perhaps I could ggsave the plots as images, then use include_graphics. Seems hacky. Worse, it'll rasterize them so they can't be zoomed in on. But, it's a thought.

dfrankow
  • 20,191
  • 41
  • 152
  • 214

1 Answers1

1

Best to use .pdfs here, since the format is designed for not to change when zooming. You simply could use the for loop or probably better Map to, first, create your plots, and, second, to produce "as-is" LaTeX code using cat. I'm using base plots here, I'm sure, you can also do this with ggplot2. Around the Map we wrap an invisible to omit console output.

---
title: "Untitled"
output: pdf_document
header-includes:
- \usepackage{lipsum}  % just used for sample loremipsum text
---

\lipsum[1]

```{r plots, echo=FALSE, results="asis"}

what <- rep("AirPassengers", 4)  ## mimicking multiple plots

invisible(Map(function(w) {
  pdf(file=paste0(w, ".pdf"))
  plot(get(w))
  dev.off()
}, what))

heights <- c(2, 4, 6, 8)  ## define heights for each plot

invisible(Map(function(w, h) cat(
"
\\begin{figure}[ht]
\\includegraphics[height=", paste0(h, "cm"), "]{", paste0(w, ".pdf"), "}
\\caption{", w, "}\\label{fig:", w, "}
\\end{figure}
", sep=""), what, heights))

```

\lipsum[1]

Produces:

enter image description here

If you really only want different heights, you can specify the dimensions in the first Map call, e.g. using a second argument for the width, and use constant height/width in the second one.

Community
  • 1
  • 1
jay.sf
  • 60,139
  • 8
  • 53
  • 110