How to put distinct colors to connection bridges in the Sankey plot ?
0
0
Entering edit mode
4 days ago
ohtang7 ▴ 40

Dear guys,

I am trying to use Sankey plot for showing correlation analysis. enter image description here

As in the figure, the bridge is only grey and black.

How can I put the colors as below figure ?

enter image description here

My code is

parasite_data <- read.csv("18S_Clr_with first row_taxafiltered.csv")
prey_data <- read.csv("12S_Clr_with first row.csv")


parasite_data <- parasite_data %>%
  rename(Parasite_Taxon = Taxa) %>%
  pivot_longer(
    cols = starts_with("Sample"),
    names_to = "Sample",
    values_to = "Parasite_Abundance"
  )

prey_data <- prey_data %>%
  rename(Prey_Taxon = Taxa) %>%
  pivot_longer(
    cols = starts_with("Sample"),
    names_to = "Sample",
    values_to = "Prey_Abundance"
  )

merged_data <- inner_join(parasite_data, prey_data, by = "Sample")

correlations <- merged_data %>%
  group_by(Parasite_Taxon, Prey_Taxon) %>%
  summarise(
    correlation = cor(Parasite_Abundance, Prey_Abundance, method = "spearman", use = "complete.obs"),
    .groups = "drop"
  ) %>%
  filter(!is.na(correlation) & abs(correlation) > 0.3)

correlations

parasite_nodes <- unique(correlations$Parasite_Taxon)
prey_nodes <- unique(correlations$Prey_Taxon)

nodes <- data.frame(
  name = c(parasite_nodes, prey_nodes),
  group = c(rep("parasite", length(parasite_nodes)), rep("prey", length(prey_nodes)))
)

# Create a lookup table for node indices
node_lookup <- data.frame(
  name = nodes$name,
  id = 0:(nrow(nodes) - 1)
)

links <- correlations %>%
  left_join(node_lookup, by = c("Parasite_Taxon" = "name")) %>%
  rename(Source = id) %>%
  left_join(node_lookup, by = c("Prey_Taxon" = "name")) %>%
  rename(Target = id) %>%
  mutate(Value = abs(correlation)) %>%
  select(Source, Target, Value)

parasite_colors <- brewer.pal(min(length(parasite_nodes), 8), "Set1")
prey_colors <- brewer.pal(min(length(prey_nodes), 8), "Set2")

colors <- c(parasite_colors, prey_colors)

jscode <- paste0(
  "d3.scaleOrdinal()",
  ".range(['", paste(colors, collapse = "','"), "'])"
)

sankey_plot <- sankeyNetwork(
  Links = links,
  Nodes = nodes,
  Source = "Source",
  Target = "Target",
  Value = "Value",
  NodeID = "name",
  colourScale = jscode,
  sinksRight = FALSE,
  fontSize = 12,
  nodeWidth = 30
)

sankey_plot

Plz any comments for revising the code. (Even Python code is welcomed to solve the problem !! )

R Python Sankey • 256 views
ADD COMMENT
0
Entering edit mode
ADD REPLY

Login before adding your answer.

Traffic: 2714 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6