Load libraries

library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.4     ✔ readr     2.1.5
## ✔ forcats   1.0.0     ✔ stringr   1.5.1
## ✔ ggplot2   3.5.1     ✔ tibble    3.2.1
## ✔ lubridate 1.9.3     ✔ tidyr     1.3.1
## ✔ purrr     1.0.2     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(ggplot2)
library(dplyr)
library(networkD3)
library(htmlwidgets)
## 
## Attaching package: 'htmlwidgets'
## 
## The following object is masked from 'package:networkD3':
## 
##     JS
library(ggalluvial)
library(readxl)

Set working directory

## [1] "/Users/sxl1405@student.bham.ac.uk/Documents/Code/assumption"

Load the nodes and links data from the Excel file

nodes <- read_excel("sharedsankey.xlsx", sheet = "Nodes")
links <- read_excel("sharedsankey.xlsx", sheet = "Links")

# Create a color scale for the links based on the 'source' (model)
links$group <- as.factor(links$source)  # Factorize the 'source' column
color_scale <- 'd3.scaleOrdinal().range(d3.schemeCategory10)'  # Use D3's Category10 color scale

Create the sankey diagram

p <- sankeyNetwork(
  Links = links,
  Nodes = nodes,
  Source = "source",
  Target = "target",
  Value = "value",
  NodeID = "name",
  units = "TWh",
  fontSize = 12,
  nodeWidth = 20,
  margin = list(left = 400, right = 0),
  LinkGroup = "group",  # This will color the links based on the 'group'
  colourScale = color_scale,  # Apply the color scale to the links
  width = 950,            # Reduced width for portrait
  height = 1000  
)
## Links is a tbl_df. Converting to a plain data frame.
## Nodes is a tbl_df. Converting to a plain data frame.
# Adjust label positioning in the diagram
p <- htmlwidgets::onRender(p, "
  function(el, x) {
    d3.selectAll('.node text')
      .style('text-anchor', 'start')
      .attr('dx', '10');
  }
")

# Display the diagram
p