sankey_test

[This article was first published on HighlandR, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

“`r library(data.table) library(dplyr) library(tidyr) library(networkD3) library(htmlwidgets) library(widgetframe) data <- data.table::fread('https://raw.githubusercontent.com/johnmackintosh/energy-closures/main/rawdata.csv') head(data,10) ``` ``` Date Failed_supplier Customers Acquired_by 1: 2022-01-01 Together Energy Retail Ltd. 176000 British Gas 2: 2021-12-01 Zog Energy 11700 EDF 3: 2021-11-01 Entice Energy Supply Ltd 5400 Scottish Power 4: 2021-11-01 Orbit Energy 65000 Scottish Power 5: 2021-11-01 Bulb 1700000 *In special administration* 6: 2021-11-01 Neon Reef Ltd. 30000 British Gas 7: 2021-11-01 Social Energy Supply Ltd. 5500 British Gas 8: 2021-11-01 CNG Energy Ltd. 41000 Pozitive Energy 9: 2021-11-01 Omni Energy Ltd. 6000 Utilita 10: 2021-11-01 MA Energy Ltd. 300 SmartestEnergy Business Ltd. ``` ```r data2 <- data %>% rename(failed = `Failed_supplier`, acquired = `Acquired_by`) %>% mutate(year_acquired = lubridate::year(Date)) %>% relocate(year_acquired, .before = ‘Date’) %>% select(-Date) links <- data2 %>% filter(year_acquired >= 2021) %>% mutate(row = row_number()) %>% gather(‘column’, ‘source’, -row) %>% mutate(column = match(column, names(data2))) %>% group_by(row) %>% arrange(column) %>% mutate(target = lead(source)) %>% ungroup() %>% filter(!is.na(target)) 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))) links$source <- match(links$source, nodes$name) - 1 links$target <- match(links$target, nodes$name) - 1 links$value <- 1 nodes$name <- sub('_[0-9]+$', '', nodes$name) p <- networkD3::sankeyNetwork(Links = links, Nodes = nodes, Source = 'source', Target = 'target', Value = 'value', NodeID = 'name') ``` ``` Links is a tbl_df. Converting to a plain data frame. ``` ```r htmlwidgets::saveWidget(p,here::here("_posts",'sankeyEnergy.html')) #widgetframe::frameWidget(p) ```

To leave a comment for the author, please follow the link and comment on their blog: HighlandR.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)