Embedding plotly graphs in a Rmarkdown document using source(“filename.R”)

家住魔仙堡 提交于 2019-12-10 22:58:48

问题


I am creating a RMarkdown HTML document where chunks are sourcing R files:

```{r }
source("test.R")
```

Where test.R is:

library(ggplot2)
library(plotly)

data <- as.data.frame(datasets::mtcars)

create_plot <- function(data, var_x, var_y, var_color, var_size) {
data %>% ggplot(aes_string(
    x = var_x, 
    y = var_y, 
    color = var_color, 
    size = var_size)) + 
    geom_point()
}

p <- create_plot(data, "disp", "qsec", "vs", "hp")

p <- ggplotly(p)

print(p)

This works inline the Rmarkdown document (RStudio) but not when I knitr the document (no plotly output shows up in the generated HTML file). I have tried several alternatives to print(p) such as:

p <- as_widget(p)
print(p)

or

p <- as_widget(p)
htmltools::tagList(p)

but no plot shows up when knitting the HTML document. No warning messages either. Any thoughts?

来源:https://stackoverflow.com/questions/45742115/embedding-plotly-graphs-in-a-rmarkdown-document-using-sourcefilename-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!