Mark Zhou
Mark Zhou

Reputation: 167

D3 Sequence Sunburst Chart on Shiny

I'm working on a project which needs to make a sequence sunburst chart. I found a sample on D3.js, but I don't know how to put it into a shiny server function. Does anyone know how to do it?

This is the link for that sunburst chart on D3: http://bl.ocks.org/kerryrodden/7090426

Upvotes: 1

Views: 2222

Answers (1)

rawr
rawr

Reputation: 20811

I should give a disclaimer that I have no idea how to use shiny.

I have a directory, test, with

  • server.R
  • ui.R
  • www/
    • sequences.js
    • sequences.css
    • index.html
    • visit-sequences.csv

First I used this function to make the visit-sequences.csv file with the data

## function to create the csv file
make_csv <- function(x, file = '~/desktop/test/www/visit-sequences.csv') {
  dd <- data.frame(ftable(x))
  dd <- within(dd, {
    visit <- apply(dd[, -ncol(dd)], 1, function(x)
      paste0(c(x, 'end'), collapse = '-'))
    count <- dd$Freq
  })

  write.table(dd[dd$count > 0, c('visit','count')], file = file, sep = ',',
              quote = FALSE, row.names = FALSE, col.names = FALSE)
}

set.seed(1)
dd <- sample(c('home','product','search','account','other'), 500,
             replace = TRUE, prob = c(.5,.3,.1,.05,.05))
dd <- as.data.frame(matrix(dd, ncol = 5))
make_csv(dd)

Note that you can see the chart already without shiny

browseURL('~/desktop/test/www/index.html')

To use in a shiny app,

server.R

## server.R
shinyServer(function(input, output) {
  ## nothing here
})

ui.R

## ui.R
shinyUI(pageWithSidebar(
  headerPanel(HTML('A sunburst chart in d3')),

  sidebarPanel(
    checkboxInput(
      inputId = 'dataSource',
      label = 'Select file.',
      value = FALSE
    ),

    conditionalPanel(
      condition = 'input.dataSource == false',
      textInput(inputId='url', label='File URL:', value='./visit-sequences.csv')
    ),

    conditionalPanel(
      condition = 'input.dataSource == true',
      fileInput(inputId = 'file', label='Data to plot:')
    )
  ),

  mainPanel(
    includeScript('./www/sequences.js'),
    includeCSS('./www/sequences.css'),
    includeHTML('./www/index.html')
  )
))

Finally, run

library('shiny')
runApp('~/desktop/test')

And I get this

enter image description here

But like I said, I don't really know what I'm doing. To change the labels, colors, and other things, you would need to edit the js, html, css files.

Upvotes: 1

Related Questions