library(tidyverse)
library(viridis)
library(patchwork)
library(hrbrthemes)
library(circlize)
library(networkD3)
library(plotly)
library(dplyr)
data <- read.csv("your_data.csv")
data<- aggregate(count ~ section + cited_section, data = data, sum)
data_long <- data #keep original data
colnames(data_long) <- c("source", "target", "value")
data_long$target <- paste(data_long$target, " ", sep="")
nodes <- data.frame(name=c(as.character(data_long$source), as.character(data_long$target)) %>% unique())
# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
data_long$IDsource=match(data_long$source, nodes$name)-1
data_long$IDtarget=match(data_long$target, nodes$name)-1
# prepare colour scale
MyColours ='d3.scaleOrdinal() .range(["#FFC0CB", "#FFD700", "#FFA07A", "#DDA0DD", "#B0E0E6", "#98FB98","#FF7F7F","#0000FF"])'
# Make the Network
sankeyNetwork(Links = data_long, Nodes = nodes,
Source = "IDsource", Target = "IDtarget",
Value = "value", NodeID = "name",
sinksRight=FALSE, colourScale=MyColours, nodeWidth=40, fontSize=13, nodePadding=20)
Trying to colour the edges & change names
# Create a vector of labels
label1 <- c("A" = "Chemistry", "B" = "Electricity", "C" = "Construction", "D" = "Textile","E" = "Performing Operations", "F" = "Mechanical Engineering", "G" = "Physics", "H" = "Human Necessities")
label2 <- c("A " = "Chemistry", "B " = "Electricity", "C " = "Construction", "D " = "Textile","E " = "Performing Operations", "F " = "Mechanical Engineering", "G " = "Physics", "H " = "Human Necessities")
# Transform the columns
data_long$source <- as.character(factor(data_long$source, levels = names(label1), labels = label1))
data_long$target <- as.character(factor(data_long$target, levels = names(label2), labels = label2))
# Define a color scale using d3.scaleOrdinal
MyColours <- 'd3.scaleOrdinal().range(["#FFC0CB", "#FFD700", "#FFA07A", "#DDA0DD", "#B0E0E6", "#98FB98", "#FF7F7F", "#0000FF"])'
# Add a new column 'SourceColor' to data_long with the source node's color
data_long$SourceColor <- htmlwidgets::JS(sprintf("%s(%s)", MyColours, data_long$source))
sankeyNetwork(
Links = data_long,
Nodes = nodes,
Source = "IDsource",
Target = "IDtarget",
Value = "value",
NodeID = "name",
sinksRight = FALSE,
colourScale = "d3.scaleOrdinal().range(['#FFC0CB', '#FFD700', '#FFA07A', '#DDA0DD', '#B0E0E6', '#98FB98', '#FF7F7F', '#0000FF'])", # Specify color scale here
nodeWidth = 40,
fontSize = 13,
nodePadding = 20,
LinkGroup = "SourceColor" # Use the SourceColor column for coloring edges
)