Plotly图不会在RMarkdown文档

时间:2018-04-23 22:10:06

标签: r r-markdown knitr plotly

我正在尝试动态构建一个需要运行循环的报表,并且每次迭代都会打印一些消息,表格和一个图表。我可以让一切工作之外的情节。

example.rmd

```{r echo=FALSE, results='asis', fig.keep='all', message = FALSE, warning = FALSE}
library(knitr)
library(plotly)

for(i in 1:4){
  foo <- iris[sample(nrow(iris), 20), ]

  cat("\n")
  cat("# Iteration", i, "\n")

  # Print the first few lines
  print(kable(head(foo)))
  cat("\n")

  # Plot Sepal.Width vs Petal.Length using ggplotly()
  plt <- ggplot(foo, aes(x = Sepal.Width, y = Petal.Length))+geom_point()

  # plot(plt)  # <- this works
  # plot(ggplotly(plt))  # <- this doesn't work
  # ggplotly(plt)  # <- this doesn't work

  cat("\n")
}
```

enter image description here

如何在报告中绘制情节图?

1 个答案:

答案 0 :(得分:7)

关于this post on github关于基本相同的问题,我能够将这个非常hacky的解决方案放在一起。很想找到更好的方法。

```{r echo=FALSE, results='asis', fig.keep='all', message = FALSE, warning = FALSE}
library(knitr)
library(plotly)

# Build list of outputs
output <- list()
for(i in 1:4){
  foo <- iris[sample(nrow(iris), 20), ]

  # Header for iteration
  txt <- paste0("#Iteration ", i)
  output[[length(output) + 1L]] <- txt

  # Table of the first few lines
  tbl <- kable(head(foo))
  output[[length(output) + 1L]] <- tbl

  # Plot
  plt <- ggplotly(ggplot(foo, aes(x = Sepal.Width, y = Petal.Length))+geom_point())
  output[[length(output) + 1L]] <- plt
}

# Render the outputs
for(j in 1:length(output)){
  x <- output[[j]]

  if(inherits(x, "character")){
    cat("\n")
    cat(x)
  } else if(inherits(x, "knitr_kable")){
    cat("\n")
    print(x)
  }
  else {
    # print the html piece of the htmlwidgets
    cat("\n")
    cat(htmltools::renderTags(as.widget(x))$html)
  }
}
```

```{r echo=FALSE, messages=FALSE, warning=FALSE}
# Attach the Dependencies since they do not get included with renderTags(...)$html
deps <- lapply(
  Filter(f = function(x){inherits(x,"htmlwidget")}, x = output),
  function(hw){
    htmltools::renderTags(hw)$dependencies
  }
)
htmltools::attachDependencies(x = htmltools::tagList(), value = unlist(deps,recursive=FALSE))
```

enter image description here