Following up with this question, how can I create an shiny app in which I can choose a person and get nodes and links related to that person only shown?. The data plot and code I tried are below:
Data
df <- read.table(header = TRUE, stringsAsFactors = FALSE, text = '
name year1 year2 year3 year4
Bob Hilton Sheraton Westin Hyatt
John "Four Seasons" Ritz-Carlton Westin Sheraton
Tom Ritz-Carlton Westin Sheraton Hyatt
Mary Westin Sheraton "Four Seasons" Ritz-Carlton
Sue Hyatt Ritz-Carlton Hilton Sheraton
Barb Hilton Sheraton Ritz-Carlton "Four Seasons"
')
Sankey plot
library(networkD3)
links <-
df %>%
mutate(row = row_number()) %>% # add a row id
pivot_longer(-row, names_to = "column", values_to = "source") %>% # gather all columns
mutate(column = match(column, names(df))) %>% # convert col names to col ids
group_by(row) %>%
mutate(target = lead(source, order_by = column)) %>% # get target from following node in row
ungroup() %>%
filter(!is.na(target)) # remove links from last column in original data
links <-
links %>%
mutate(source = paste0(source, '_', column)) %>%
mutate(target = paste0(target, '_', column + 1)) %>%
select(source, target)
nodes <- data.frame(name = unique(c(links$source, links$target)))
nodes$label <- sub('_[0-9]*$', '', nodes$name) # remove column id from node label
links$source_id <- match(links$source, nodes$name) - 1
links$target_id <- match(links$target, nodes$name) - 1
links$value <- 1
sankeyNetwork(Links = links,
Nodes = nodes,
Source = 'source_id',
Target = 'target_id',
Value = 'value',
NodeID = 'label',
LinkGroup = "source",
NodeGroup = "name",
fontSize = 20,
nodeWidth = 10)
Unsuccessful shiny app code
ui <- fluidPage(
selectInput(inputId = "name",
label = "name",
choices = c("Bob", "John","Tom","Mary","Sue","Barb")),
sankeyNetworkOutput("diagram")
)
server <- function(input, output) {
links <- links
links
nodes <- nodes
nodes
links2 <-reactive({
links %>%
filter(source ==df$name )
})
output$diagram <- renderSankeyNetwork({
sankeyNetwork(
Links = links2,
Nodes = nodes,
Source = 'source_id',
Target = 'target_id',
Value = 'value',
NodeID = 'label',
LinkGroup = "source",
NodeGroup = "name",
fontSize = 20,
nodeWidth = 10,
sinksRight = FALSE
)
})
}
shinyApp(ui = ui, server = server)
In the siney app, I want to select the person and see the sanky diagram related to that person only i,e, choose all nodes and links related to that person. For example, it will be something like picture below for "Tom".