user3510503
user3510503

Reputation: 358

Multiple Plot outputs from a function in rmarkdown

I have a function that produces 2 chart objects and I'd like to use this function in an rmarkdown file and knit it so that I get an HTML report. The problem I'm facing is that when I use this function, I get an output that looks something like this:

enter image description here

Here "Plot1" and "Plot2" are the actual plots that get rendered. What changes to I need to make so that I only get the following?

Plot1 Plot2

Here is the code chunk from my R-markdown file.

```{r OverallGRP106_trended_fav, echo=FALSE, fig.align="center", message=FALSE, warning=FALSE, paged.print=TRUE}
trended_fav(psc_surv,"Overall","GRP106")
```

The return statement of function "trended_fav" is as follows:

return(list(plot(p4), plot(p1)))

Upvotes: 1

Views: 1790

Answers (1)

Jon Spring
Jon Spring

Reputation: 67010

I think you'll be ok if you assign the function's output to a variable and then call up the element of the variable separately, like so:

---
output: html_document
---

```{r setup, include=FALSE}
library(ggplot2)
trended_fav <- function() {
  p4 <- ggplot(mtcars, aes(mpg, wt)) + geom_point()
  p1 <- ggplot(txhousing, aes(year, median)) + geom_point()
  plot_list <- list(p4,p1)
  return(plot_list)
}
a <- trended_fav()
```

## First report

Here it is:

```{r}
a[1]
```

## Second report

This one is even better:

```{r}
a[2]
```

Upvotes: 3

Related Questions