我正在使用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 回答
事实证明问题在这里得到解决https://github.com/ropensci/plotly/issues/273
knitr已知在循环中打印图表图表的问题 . 从这里引用最终答案cpsievert
我有几个替代方案 . 如果它有用,请告诉我!
Suggestion1(基础
plotly
使用subplot
):