sankeyNetwork is invisible in Shiny R

Viewed 58

[SOLVED]

I am trying to do a ShinyApp using some examples from the internet. As part of my app I want to plot a Sankey Diagram, however, I have been finding a problem.

My app has a navbarPage structure and uses the example from https://github.com/jienagu/D3_folded_charts as one of the primary tabs. After some tests, I figured out that the sankeyNetwork was in conflict with the code part of the bar graph in the example above (specifically with this part: lines 147-149):

output$airbar = renderD3({ bar_graphD3() })

This is the code I am using to render the Sankey diagram:

  output$diagram <- networkD3::renderSankeyNetwork({
networkD3::sankeyNetwork(Links = dispersores_df, 
                         Nodes = nodes,
                         Source = "IDsource", 
                         Target = "IDtarget",
                         Value = "value", 
                         fontSize = 20,
                         NodeID = "name", 
                         sinksRight=FALSE) 

})

Since this bar graph function is very important for my app, I can't remove it.

Also, due to the fact that the console doesn't pop up any error message, I realized the sankeyNetwork was been rendered. So, I changed my app structure to the fluidPage() and I found the Sankey graph was there (but it was not interactive) as you can see in the figure below.

Sankey visualized in the fluidPage() structure

After changing back to navbarPage() I inspected the tab the Sankey was, and it looks like it is there but invisible.

Sankey invisible in the navbarPage() structure

I found a similar report here sankeyNetwork through renderUI disappears when applying JScode to remove viewbox with htmlwidgets::onRender() but its solution didn't work for me.

Does anyone have any idea or clues that could help me?

Thanks

Full code here:

# library ------------------------------------------------------------------


if(!require("devtools")) install.packages("devtools", dependencies = TRUE)
if(!require("shiny")) install.packages("shiny", dependencies = TRUE)
if(!require("janitor")) install.packages("janitor", dependencies = TRUE)
if(!require("tidyverse")) install.packages("tidyverse", dependencies = TRUE)
if(!require("purrr")) install.packages("purrr", dependencies = TRUE)
if(!require("rlang")) install.packages("rlang", dependencies = TRUE)
#if(!require("stringr")) install.packages("stringr", dependencies = TRUE)
if(!require("noteMD")) devtools::install_github("jienagu/noteMD")
#if(!require("DT")) install.packages("DT", dependencies = TRUE)
if(!require("r2d3")) install.packages("r2d3", dependencies = TRUE)
if(!require("webshot")) install.packages("webshot", dependencies = TRUE)
if(!require("htmlwidgets")) install.packages("htmlwidgets", dependencies = TRUE)
#if(!require("memor")) install.packages("memor", dependencies = TRUE)
if(!require("shinyjs")) install.packages("shinyjs", dependencies = TRUE)
if(!require("nivopie")) devtools::install_github("jienagu/nivopie")
#if(!require("shinythemes")) install.packages("shinythemes", dependencies = TRUE)
#webshot::install_phantomjs()
#tinytex::install_tinytex()
if(!require("leaflet")) install.packages("leaflet", dependencies = TRUE)
#if(!require("performance")) install.packages("performance", dependencies = TRUE)
if(!require("shinyWidgets")) install.packages("shinyWidgets", dependencies = TRUE)
#if(!require("rmarkdown")) install.packages("rmarkdown", dependencies = TRUE)
if(!require("networkD3")) devtools::install_github("christophergandrud/networkD3")
#if(!require("stats")) install.packages("stats", dependencies = TRUE)
#if(!require("stargazer")) install.packages("stargazer", dependencies = TRUE)
#if(!require("caret")) install.packages("caret", dependencies = TRUE)
#if(!require("sjPlot")) install.packages("sjPlot", dependencies = TRUE)
#if(!require("sjlabelled")) install.packages("sjlabelled", dependencies = TRUE)
#if(!require("sjmisc")) install.packages("sjmisc", dependencies = TRUE)


# ui ----------------------------------------------------------------------

col.list <- c("white")
colors <- paste0("background:",col.list,";")


ui <- bootstrapPage(
  div(style="display:inline-block", img(src="gif_trees_birds_grid_reseed.gif", 
                                         style="position: header; width: 100%; margin-left:0%; margin-top: 0%")),
  shinythemes::themeSelector(),
  navbarPage(
    theme = shinytheme("sandstone"),
    title = "Atlantic forest plant traits",
    setBackgroundColor(color = c("#FFF5EE")),
    
    
    #header = tagList(
    #  useShinydashboard()
    #),
    
                        

# Pie graph ---------------------------------------------------------------
    
    tabPanel(title = "Traits Summary",
             sidebarLayout(
               sidebarPanel(
                 selectInput(
                   inputId = "species",
                   label = "Species:",
                   selected = "Acnistus arborescens",
                   choices = c(unique(plant_traits$species)),
                   size = 25, selectize = FALSE
                 )
               ),
               
               # Show a plot of the generated distribution
               mainPanel(
                 tabsetPanel(
                   id = "tabs",
                   tabPanel(
                     title = "Analytics Dashboard",
                     value = "page1",
                     useShinyjs(),
                     checkboxInput("OneMore", label = h5("Show and Report donut Chart?"), T),
                     fluidRow(
                       column(
                         width = 6,
                         d3Output("traitbar")
                       ),
                       div(id='Hide',
                           column(
                             width = 6,
                             nivopieOutput("traitpie")
                           )
                       )
                     )
                   )
                 )
               )
             )
    ),


# dispersers --------------------------------------------------------------
    
        tabPanel(title = "Dispersers",
                   mainPanel(
                     tabsetPanel(type = "hidden",
                                 tabPanel("Animal dispersers",
                                          networkD3::sankeyNetworkOutput("diagram", 
                                                                         height = "700px", 
                                                                         width = "100%")))
                     
           ))


  )
)


# Define server logic required to draw a histogram
server <- function(input, output) {
  
  
  # Trait summary -----------------------------------------------------------
  
  
  shinyjs::useShinyjs()
  observe({
    shinyjs::toggle(id = "Hide", condition = input$OneMore, anim = TRUE, animType = "fade")
  })
  plant_traits_filtered <- reactive({
    if (input$species != "ALL") plant_traits <- dplyr::filter(plant_traits, species == input$species)
    plant_traits
  })
  
  bar_graphD3 <- reactive({
    grouped <- ifelse(input$species != "ALL", expr(plant_traits), expr(species))
   
    spptraitdata <- plant_traits_filtered() %>%
      dplyr::group_by(!!grouped) %>%
      dplyr::tally() %>%
      dplyr::collect() %>%
      dplyr::mutate(
        y = n,
        x = !!grouped) %>%
      dplyr::select(x, y)

    spptraitdata <- spptraitdata %>%
      dplyr::mutate(label = x)
    
    r2d3::r2d3(spptraitdata, "bar_plot.js")
  })
  
  pie_graph <- reactive({
    grouped2 <- ifelse(input$species != "ALL", expr(plant_traits), expr(species))
    
    spptraitdata2 <- plant_traits_filtered() %>%
      dplyr::group_by(!!grouped2) %>%
      dplyr::tally() %>%
      dplyr::collect() %>%
      dplyr::mutate(
        value = n,
        id = !!grouped2) %>%
      dplyr::select(id, value)
    
    spptraitdata3 <- data.frame(spptraitdata2)
    spptraitdata3$id <- as.factor(spptraitdata3$id)
    nivopie::nivopie(spptraitdata3, innerRadius=0.5, cornerRadius=5, fit=T, sortByValue=T,
            colors='paired', enableRadialLabels=F, radialLabelsLinkDiagonalLength=1,
            radialLabelsLinkHorizontalLength=8,
            enableSlicesLabels=T, sliceLabel='id',isInteractive=T)
    
  })

  output$traitbar = r2d3::renderD3({
    bar_graphD3()
  })

  output$traitpie=nivopie::renderNivopie({
    pie_graph()
  })
  
  # plant/trait bar click (server) ---------------------------------
  observeEvent(input$bar_clicked != "", {
    if (input$species == "ALL") {
      updateSelectInput(session, "species", selected = input$bar_clicked)
    }
  }, ignoreInit = TRUE)
  

# sankeyNetwork diagram plot ------------------------------------------------------

  
  output$diagram <- networkD3::renderSankeyNetwork({
    networkD3::sankeyNetwork(Links = dispersores_df, 
                             Nodes = nodes,
                             Source = "IDsource", 
                             Target = "IDtarget",
                             Value = "value", 
                             fontSize = 20,
                             NodeID = "name", 
                             sinksRight=FALSE) #%>% 
#      htmlwidgets::onRender('function(el) { el.querySelector("svg").removeAttribute("viewBox") }')
    
  })
}
# Run the application
shinyApp(ui = ui, server = server)
0 Answers
Related