首页 文章

在for循环中绘制Plotly图表

提问于
浏览
2

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

在下面的代码中,plotChart函数返回一个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语句更改为 print(ggplotly(p)) ,它就不会在html中打印图表 . 该代码完美地在knitr之外工作 .

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

EDIT:

包括下面的可重现的例子 . 以下是我的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语句更改为 `print(ggplotly(ggplot(s,aes(x = x, y = y)) + geom_point()))` 就会生成一个空白的html而没有任何错误 . 

在终端中运行相同的代码可以很好地工作

```java
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()))
}

感谢任何帮助 .

谢谢,Kaustubh

2 回答

  • 2

    事实证明问题在这里得到解决https://github.com/ropensci/plotly/issues/273

    knitr已知在循环中打印图表图表的问题 . 从这里引用最终答案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,谢谢你的帮助 . 我创建了一个虚拟数据集,只是为了创建一个可重现的例子 . 虽然您的解决方案可能解决了虚拟示例,但在当前问题中并非与我相关 . 我认为这里提供的解决方案应该是通用的 . 
    
    谢谢,Kaustubh
  • 5

    我有几个替代方案 . 如果它有用,请告诉我!

    Suggestion1(基础 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
    
    
    
    Suggestion2(使用 `ggplot2` ,但使用 `facet` ):
    
    ```java
    ```{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~.))
    
    

相关问题