在 for 循环中绘制图表

Plotly charts in a for loop

我正在使用 plotly 转换 ggplot2 图表并将它们放入 knitr html 输出中。 这是报告的工作副本。 http://rpubs.com/kausti/NSEFO-23-Mar-2016 第一个图表是 plotly 图表,而以下图表不是。我希望它们是图表,但我被卡住了。

在下面的代码中,plotChart 函数 returns ggplot2 图。此代码有效!

for (tick in tradeOps$ticker)
{
  tmpDF = filter(tradeOps, ticker == tick)
  p = plotChart(tick = tick,Entry = tmpDF$Entry, Target =     tmpDF$Target, SL= tmpDF$SL, TradeType = tmpDF$TradeType, data = wd)
  p = p + annotate("text", x = as.Date(tmpDF$Date)+30, y =   tmpDF$Entry, label = tmpDF$Entry, colour = "blue")
  p = p + annotate("text", x = as.Date(tmpDF$Date)+30, y = tmpDF$Target, label = tmpDF$Target)
  p = p + annotate("text", x = as.Date(tmpDF$Date)+30, y = tmpDF$SL, label = tmpDF$SL)

  print(p)

}

现在,如果我将最后一个打印语句更改为 print(ggplotly(p)),它就不会打印 html 中的图表。 该代码在 knitr 之外完美运行。

此外,print(ggplotly(p)) 在循环外也能完美运行。 我错过了什么吗?

编辑:

包括以下可重现的示例。 以下是我的 rmd 文件。

---
title: "tmp"
output: html_document
---

```{r, echo=FALSE, message=FALSE, fig.width=8, fig.height=6}
library(ggplot2)
library(plotly)
library(dplyr)
s = NULL
a = data.frame(id = 1:15,x = 2:16, y = 15:1, z = c(rep("a",5),rep("b",5),rep("c",5)))
for(i in unique(a$z)){
  s = a[a$z == i,]
  print(ggplot(s,aes(x = x, y = y)) + geom_point())
}

```

这与显示三个图形的输出 html 完美配合。 现在,只需将最后一个打印语句更改为 print(ggplotly(ggplot(s,aes(x = x, y = y)) + geom_point())) 生成空白 html,没有任何错误。

运行 终端中的相同代码虽然可以完美运行

library(ggplot2)
library(plotly)
library(dplyr)
s = NULL
a = data.frame(id = 1:15,x = 2:16, y = 15:1, z = c(rep("a",5),rep("b",5),rep("c",5)))
for(i in unique(a$z)){
  s = a[a$z == i,]
  print(ggplotly(ggplot(s,aes(x = x, y = y)) + geom_point()))
}

感谢任何帮助。

谢谢, 考斯图布

我有两种选择供您选择。让我知道是否有帮助!

建议 1(基础 plotly 使用 subplot):

```{r, echo=FALSE, message=FALSE, fig.width=8, fig.height=6}
library(ggplot2)
library(plotly)
library(dplyr)
s = NULL
a = data.frame(id = 1:15,x = 2:16, y = 15:1, z = c(rep("a",5),rep("b",5),rep("c",5)))
a$id2 <- as.integer(a$z)
p <- plot_ly(a, x = x, y = y, group=z, xaxis = paste0("x", id2), mode = "markers")
p <- subplot(p, nrows=3)
p

```

建议 2(使用 ggplot2 但使用 facet):

```{r, echo=FALSE, message=FALSE, fig.width=8, fig.height=6}
library(ggplot2)
library(plotly)
library(dplyr)
s = NULL
a = data.frame(id = 1:15,x = 2:16, y = 15:1, z = c(rep("a",5),rep("b",5),rep("c",5)))
ggplotly(ggplot(a,aes(x = x, y = y)) + geom_point() + facet_grid(z~.))

```

原来问题到这里就解决了 https://github.com/ropensci/plotly/issues/273

knitr 在循环打印 plotly 图表时存在已知问题。 从这里引用最终答案 cpsievert

```{r}
l <- htmltools::tagList()
for (i in 1:3) {
  l[[i]] <- as.widget(plot_ly(x = rnorm(10)))
}
l
```

这解决了我的问题。虽然在我找到这个解决方案之前,我最终将所有东西从 ggplot2 移植到 plotly R api。

MLavoie,感谢您的帮助。我生成了一个虚拟数据集只是为了创建一个可重现的示例。尽管您的解决方案可能解决了虚拟示例,但在当前问题中与我无关。我认为这里提供的解决方案应该是通用的。

谢谢, 考斯图布