timelyportfolio/sunburstR

Sunburst doesn't display in for loop

jules-chstlr opened this issue · 3 comments

I would like to display (and save as a HTML file) a sunburst computed in a for loop.

Here is an example of what I would like to do (data from https://cran.r-project.org/web/packages/sunburstR/sunburstR.pdf) :

library(sunburstR)

sequences <- read.csv(
  system.file("examples/visit-sequences.csv",package="sunburstR")
  ,header = FALSE
  ,stringsAsFactors = FALSE
)[1:100,]

for (i in c(1,2,3)) {
  sunburst(sequences)
}

It should display the same sunburst 3 times, but it doesn't display anything (in RStudio "Viewer"). I tried to save the figures as HTML files :

library(sunburstR)
library(htmlwidgets)

sequences <- read.csv(
  system.file("examples/visit-sequences.csv",package="sunburstR")
  ,header = FALSE
  ,stringsAsFactors = FALSE
)[1:100,]

for (i in c(1,2,3)) {
  sb = sunburst(sequences)
  saveWidget(sb, paste("sunburst", i, ".html", sep=""))
}

but it still doesn't work out.
Do you know if sunburst() supports for loops ? And under which circumstances ?

Thanks a lot.

@juleschassetuillier this is a common problem and a little unintuitive. I tried to answer in code. Please let me know if not clear or off the mark.

library(sunburstR)
library(htmlwidgets)

sequences <- read.csv(
  system.file("examples/visit-sequences.csv",package="sunburstR")
  ,header = FALSE
  ,stringsAsFactors = FALSE
)[1:100,]


# htmlwidgets return invisibly inside a for loop
#   so to see in RStudio viewer we need to force with print
for (i in c(1,2,3)) {
  print(sunburst(sequences))
}

# but I think the objective is something more like this
#   for Rmarkdown contexts or similar
library(htmltools)
htmltools::browsable(
  htmltools::tagList(
    lapply(1:3, function(x){
      sunburst(sequences)
    })
  )
)

# or a little more complicated
library(htmltools)
htmltools::browsable(
  htmltools::tagList(
    lapply(1:3, function(x){
      tags$div(
        style = "width:33%; display:inline-block;", # better with flexbox
        tags$h3(paste0("sunburst ", x)),
        sunburst(sequences, width = "100%")
      )
    })
  )
)

I am closing. Please re-open if the example does not provide a solution.

Thanks a lot for your reply ! It helped a lot :)

I was wondering, is it also possible to save the sunburst as a html or png/jpeg file while in a for loop ?
I tried to achieve that by using the savewidget function from htmlwidgets library, but it did not save the figures properly (it gave just some html code)

library(sunburstR)

sequences <- read.csv(
  system.file("examples/visit-sequences.csv",package="sunburstR")
  ,header = FALSE
  ,stringsAsFactors = FALSE
)[1:100,]

for (i in c(1,2,3)) {
  sb = sunburst(sequences)
  print(sb)
  saveWidget(sb, paste(getwd(), "\\sunburst_", i, ".html", sep=""))
}

Do you know a way of forcing R to save those figures ?

Thank you very much again.