RMarkdown: Multiple ggplots in same chunk using loop

Karthik :

I am trying to generate multiple plots (in ggplot2) using a for loop within a single chunk in an RMarkdown document.

When I hardcode the code to generate the two plots, the plots are rendered as expected. See section in my code titled "Hardcoded Method".

But, when I load the parameters for the two plots in a list and loop through the list, the plots are not showing up. I don't see any errors either. Please see section of my code titled "Loop Method".

Can anyone please tell me what is going on and how I can fix it? Thanks.

  • Karthik.

Here is my code:

---
title: "Test for multiple plots"
author: "KC"
date: "4/3/2020"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

# Hardcoded Method

Sample Plot - One plot at a time 

```{r Multiple Plots separately listed, echo=TRUE, fig.keep="all"}
library(ggplot2)
library(datasets)

combo = c("temperature", "pressure")
ggplot(pressure, 
       mapping=aes(x=base::get(combo[1]), y=base::get(combo[2]))) + 
  geom_point() + 
  labs(x=combo[1], 
       y=combo[2], 
       title=paste("Hardcoded Method:", paste(combo, collapse=" vs ")))

combo = c("pressure", "temperature")
ggplot(pressure, 
       mapping=aes(x=base::get(combo[1]), y=base::get(combo[2]))) + 
  geom_point() + 
  labs(x=combo[1], 
       y=combo[2], 
       title=paste("Hardcoded Method:", paste(combo, collapse=" vs ")))

```

# Loop Method

Now, I use a loop method to generate the same plots.  

```{r Multiple Plots in a loop, echo=TRUE, fig.keep="all"}
library(ggplot2)
library(datasets)
combos = list(c("temperature", "pressure"), c("pressure", "temperature"))

for (combo in combos) {
  # combo = combos[[1]]
  print(paste("Plotting", paste(combo, collapse=" vs ")))
  ggplot(pressure, 
         mapping=aes(x=base::get(combo[1]), y=base::get(combo[2]))) + 
    geom_point() + 
    labs(x=combo[1], 
         y=combo[2], 
         title=paste("Loop Method:", paste(combo, collapse=" vs ")))
}

```
chemdork123 :

When using a for loop in a code chunk with Markdown files, you need to explicitly print() the plot. So, the following code would not work:

for (i in length(x)) {
    ggplot(...)
}

You need to convert to something like this:

for (i in length(x)) {
    p <- ggplot(...)
    print(p)
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=397646&siteId=1