Hello,
I am working on an Markdown project, where i need to plot multible networkD3 Sanky-network-plots in a for loop. But when i knit the poject to an html the plots wont show in the document. The wired part is when i call the function which generates the Sanky-Plot outside the for loop the results are shown.
Here i have made a very simple version of my code. (NOTE here the function MakeSanky dose nothing special and just returns the same plot for each i, for my case the function is in a different file with several parameters):
---
output:
html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(networkD3)
library(data.table)
library(dplyr)
library(tidyverse)
library(ggplot2)
library(knitr)
MakeSanky <- function(year){
links <- data.frame(
source=c("group_A","group_A", "group_B", "group_C", "group_C", "group_E"),
target=c("group_C","group_D", "group_E", "group_F", "group_G", "group_H"),
value=c(2,3, 2, 3, 1, 3)
)
# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodes <- data.frame(
name=c(as.character(links$source),
as.character(links$target)) %>% unique()
)
# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
links$IDsource <- match(links$source, nodes$name)-1
links$IDtarget <- match(links$target, nodes$name)-1
# Make the Network
p <- sankeyNetwork(Links = links, Nodes = nodes,
Source = "IDsource", Target = "IDtarget",
Value = "value", NodeID = "name",
sinksRight=FALSE)
return(p)
}
title: "Test:"
output: bookdown::html_document2
editor_options:
chunk_output_type: console
\newpage
year <- c("2014", "2015", "2018")
print("Here the plots are missing")
for(i in year){
cat(i)
cat('\n\n')
g <- MakeSanky(i)
print(g)
cat('\n\n')
}
print("This plots are shown correct")
MakeSanky(year[1])
MakeSanky(year[2])
MakeSanky(year[3])
As you can see if i call the function ouside the loop it works, if i call it inside the for loop no plots are shown. Maybe you can help me on this problem?