Search code examples
rknitrnetworkd3xaringan

Read a Sankey Diagram from a html file


I am making slides in the R package Xaringan and I want to present a few Sankey diagrams. I have them in a folder as html files. How can I load the diagrams into my presentation?


Solution

  • This has to do with reading html files into an Rmd file. Start with creating and saving a Sankey Network:

    # this is from the help section of NetworkD3)
    library(networkD3)
    # Load energy projection data
    URL <- paste0('https://cdn.rawgit.com/christophergandrud/networkD3/',
                  'master/JSONdata/energy.json')
    energy <- jsonlite::fromJSON(URL)
    
    sn <-sankeyNetwork(Links = energy$links, Nodes = energy$nodes, Source = 'source',
                 Target = 'target', Value = 'value', NodeID = 'name',
                 units = 'TWh', fontSize = 12, nodeWidth = 30)
    
    saveNetwork(sn,"Sankey.html")
    

    Then create an Rmd file and do the following recomended by hrbrmstr in his answer to a similar question.

    ---
    title: "Read Sankey into Rmarkdown file"
    author: "user"
    output: html_document
    ---
    
    Read a Sankey diagram into a Rmd file
    ```{r Sankey, results='asis'}
    tmp <- URLencode(paste(readLines(paste(getwd(),"Sankey.html",sep = "/")), collapse="\n"))
    cat('<iframe src="data:text/html;charset=utf-8,', tmp ,'" style="border: solid; seamless:seamless; width: 100%; height: 200px"></iframe>')