【问题标题】:Several ggplotly figures from within if block in rmarkdownrmarkdown中的if块内部的几个ggplotly数字
【发布时间】:2017-02-27 22:37:53
【问题描述】:

我无法从 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...

欢迎提出建议!!

【问题讨论】:

  • 也许您可以为每个绘图命名并使用 subplot 为每个页面显示两个图表
  • this 问题是否相关?如果您在简单的 R 脚本而不是 Rmd 块中从 if 中调用它,该图会出现吗?
  • @MLavoie 我尝试了 subplot 但无法让它有一个工作布局:2 个图的传说混淆了> 此外,我真的很想显示单独的图...
  • @juod: 在 if 块之外,两个图都显示在 RStudio 的查看器窗格中(我使用的环境),而在 if 块内,只有最后一个显示在查看器中:-(
  • @juod:您上面提到的链接有一个非常人为的解决方法。如果没有其他更清洁的建议出现,我可能会尝试一下,虽然不情愿......

标签: ggplot2 r-markdown plotly


【解决方案1】:

现在可以从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))
    }
    

【讨论】:

  • 我不明白为什么不执行整个块的原因。此外,给定的链接没有解释有关 OP 问题的任何内容。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-06
  • 2020-06-05
  • 1970-01-01
  • 2020-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多