在rmarkdown中if块中的几个ggplotly数字

时间:2017-02-27 22:37:54

标签: ggplot2 r-markdown plotly

我无法从rmarkdown生成html文件,该文件显示在给定代码块中的if块内创建的两个或更多ggplotly图。

我的MWE rmarkdown源代码如下:

---
title: Several ggplotly figures from within if block in rmarkdown
author: "Mauricio Calvao"
date: "February 27, 2017"
output:
    html_document: default
---

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

```{r}
library(ggplot2)
library(plotly)
```


## Outside if block:

I can have rmarkdown generate an html document with two ggplotly plots, outside of an if block in a given chunk:

```{r}
ggplotly(qplot(data = pressure, x = temperature, y = pressure))
ggplotly(qplot(data = pressure, x = pressure, y = temperature))
```

## Inside if block:

However, when I try the same code inside an if block, only the last plot shows up in the html document:

```{r}
if (TRUE) {
ggplotly(qplot(data = pressure, x = temperature, y = pressure))
ggplotly(qplot(data = pressure, x = pressure, y = temperature))
}
```



**How do I print two (or more plots, for that matter) from within an if block in the html document???**

The above is a MWE, but, in fact, in a more general setting I would have a large number of plots to be printed depending on several if else blocks...

欢迎任何建议!!

1 个答案:

答案 0 :(得分:0)

现在可以从plotly reference获得答案。 简而言之,您可以使用:

  • 子图:
    if (TRUE) {
     p1= ggplotly(qplot(data = pressure, x = temperature, y = pressure))
     p2= ggplotly(qplot(data = pressure, x = pressure, y = temperature))
     subplot(p1, p2)
    }
    
  • 或标签列表
    if (TRUE) {
     p1= ggplotly(qplot(data = pressure, x = temperature, y = pressure))
     p2= ggplotly(qplot(data = pressure, x = pressure, y = temperature))
     htmltools::tagList(list(p1, p2))
    }