R Markdown

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com.

When you click the Knit button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:

# Define nodes
nodes <- data.frame(name =  #sources
                      c("Phthalates", "Phenols", " ", "Organic Solvents", #0-3 removed Parabens bc no links
                        "Heavy Metals", "Air Pollution", "Depression", #4-6
                        "Perceived  Stress", "Cigarette Smoke", #7-8
                        "Alcohol Consumption", "Physical Activity", #9-10
                        "Dietary Pesticides", "Caffeine Consumption", #11-12
                        "Roadway Proximity", "Indoor Air Temperature", #13-14
                        #targets : symptoms
                        "Vasomotor", "Sleep", "Cognitive", "Cardiovascular", #15-18
                        "Uro-vaginal", "Physical", "Depressed", "Anxious",#20-23
                        "Metabolic", #24
                            #more specific symptoms
                        "Hot flashes", "Night sweats", #25-26
                        "Sleep quality", "Insomnia", "Sleep duration", #27-29
                        "Forgetfulness", " ", "Heart discomfort", #30-32 removed Mental exhaustion because no links
                        "Sexual problems", "Bladder problems", "", #33-35 removed "Vaginal dryness" bc no links
                        "", "Joint and muscular discomfort", "Lung function", "", #36-38 removed Physical exhaustion and Headaches bc no links 
                        "Depressive mood", "Irritability", "Axiety", #39-41  
                        "Body weight/BMI change", "Body fat change" #42-43
                        ))
nodeNo <- 0:(nrow(nodes)-1)
nodeDf <- cbind(nodes, nodeNo)

#pared down symptoms
nodes <- data.frame(name =  #sources
                      c("Phthalates", "Phenols", " ", "Organic Solvents", #0-3 removed Parabens bc no links
                        "Heavy Metals", "Air Pollution", "", #4-5
                        "", "", #6- 7 deleted broader exposures
                        "", "", #8-9
                        "Dietary Pesticides", "", #10-11
                        "", "", #12-13
                        #targets : symptoms
                        "Vasomotor", "Sleep disturbances", "Cognitive", "Cardiovascular", #14-17 
                        "", "Respiratory", "Psychological", "Other",#  18-21
                        "Metabolic", #21
                            #more specific symptoms
                        "Hot flashes", "Night sweats", #25-26
                        "Sleep quality/Restless sleep", "Insomnia/Difficulty sleeping", "Sleep duration", #27-29
                        "Forgetfulness", " ", "Heart discomfort", #30-32 removed Mental exhaustion because no links
                        "", "", "", #33-35 removed "Vaginal dryness" bc no links
                        "", "Joint and muscular discomfort", "Lung function", "", #36-38 removed Physical exhaustion and Headaches bc no links 
                        "Depressive mood", "Irritability", "Axiety", #39-41  
                        "Body weight/BMI change", "Body fat change" #42-43
                        ))
nodeNo <- 0:(nrow(nodes)-1)
nodeDf <- cbind(nodes, nodeNo)

# Define links with positive, negative, and mixed associations
links <- data.frame(source = c(
  0, 3, 5, 6, 7, 8, 14, 
  9, 10, 12, 0, 1, 3, 5, 7, 8, 
  13, 10, 4, 3, 7, 10, 8, 12, 
  5, 7, 8, 10, 
  7, 8, 10, 10,
  3, 4, 3, 0, 11),
                    
  target = c(
    15, 15, 15, 15, 15, 15, 15, 
    15, 15, 15, 16, 16, 16, 16, 16, 16, 
    16, 16, 16, 17, 17, 17, 17, 17, 
    18, 18, 18, 18, 
    19, 19, 19, 20, 
    21, 21, 22, 23, 23),
          
  value = c(
    1, 1, 1, 1, 1, 1, 1,
    1, 1, 1, 1, 1, 1, 1, 1, 1, 
    1, 1, 1, 1, 1, 1, 1, 1, 
    1, 1, 1, 1, 
    1, 1, 1, 1, 
    1, 1, 1, 1, 1),
    
  association = c(
    "positive", "positive", "positive", "positive", "positive", "positive", "positive",
    "negative", "mixed", "mixed", "positive", "positive", "positive", "positive", "positive", "positive", 
    "positive", "negative", "mixed", "positive", "positive", "positive", "positive", "positive", 
    "positive", "positive", "positive", "negative", 
    "positive", "positive", "negative", "negative", 
    "negative", "positive", "negative", "positive", "mixed"))

write.csv(links, "~/OneDrive - California State University East Bay/Research/sankeyMenopause/links.csv", row.names = FALSE, )

links <- read.csv("~/OneDrive - California State University East Bay/Research/sankeyMenopause/linksAdd.csv", header = TRUE)

linksCondense <- read.csv("~/OneDrive - California State University East Bay/Research/sankeyMenopause/linksCondense.csv", header = TRUE)


# Add color based on association
links$color <- ifelse(links$association == "positive", "green", 
                      ifelse(links$association == "negative", "red", "yellow"))

nodes$NodeGroup <- c(rep("blue", 15), rep("gray", 29))

color_scale <- 'd3.scaleOrdinal().domain(["green", "red", "yellow", "blue", "gray"]).range(["#009E73", "#D55E00", "#F0E442", "#5b5c63", "#5D76C3"])'


#(["#4c732a", "#8c2623", "#996e18", "#262e66", "#5b5c63"])'
nodes$x[16:24] <- nodes$x[16:24] - 0.5

# Create Sankey diagram
sankey <- sankeyNetwork(Links = links, Nodes = nodes, Source = "source", Target = "target", Value = "value", NodeID = "name", units = "T", fontSize = 12, fontFamily = "serif", nodeWidth = 20, LinkGroup = "color", colourScale = color_scale, NodeGroup = "NodeGroup", margin = list("left"=190), width = 650)



sankey
  #                      , width = 500, height = 500)


# Add custom CSS to adjust label positions/ wider distance 
# htmlwidgets::onRender(sankey, '
#   function(el, x) {
#     d3.selectAll(".node text")
#       .attr("x", function(d) {
#         if (d.x + d.dx >= x.size[0] - 30) {
#           return d.x + d.dx + 10;  // Far right nodes
#         } else {
#           return d.x + d.dx + 10;  // Other nodes
#         }
#       })
#       .attr("text-anchor", "start")
#       .style("font-size", "12px");
#   }
# ')



#successfully puts labels all on right side
sankey$x$nodes <-
  sankey$x$nodes %>% 
  mutate(is_source_node = name %in% links$source)

htmlwidgets::onRender(
  sankey,
  '
  function(el,x) {
  d3.select(el)
    .selectAll(".node text")
    .filter(function(d) { return d.is_source_node; })
    .attr("x", x.options.nodeWidth)
    .attr("text-anchor", "end");
  
  d3.select(el)
    .selectAll(".node text")
    .filter(function(d) { return !d.is_source_node; })
    .attr("x", 2+ x.options.nodeWidth)
    .attr("text-anchor", "start");
  }
  '
)
sankeyCondense <- sankeyNetwork(Links = linksCondense, Nodes = nodes, Source = "source", Target = "target", Value = "value", NodeID = "name", units = "T", fontSize = 14, fontFamily = "serif", nodeWidth = 40, LinkGroup = "color", colourScale = color_scale, NodeGroup = "NodeGroup", margin = list("left"=120),  width = 600, height = 500)

# Plot the Sankey diagram
sankey
#saveNetwork(sankey, "sankey.html")
# you convert it as png
#webshot("sankey.html","sankey.png", vwidth = 1200, vheight = 900)

#sankeyCondense


# Customize the legend manually
legend <- tags$div(style = "display: flex; flex-direction: column; padding-left: 10px; margin-top: 12px; font-family: serif;",  # Adjust font and spacing

                   tags$div(style = "display: flex; align-items: center; margin-bottom: 2px;",
                            tags$div(style = "width: 12px; height: 12px; background-color: #009E73;"), "Positive association"),
                   tags$div(style = "display: flex; align-items: center; margin-bottom: 2px;",
                            tags$div(style = "width: 12px; height: 12px; background-color: #D55E00;"), "Negative association"),
                   tags$div(style = "display: flex; align-items: center; margin-bottom: 2px;",
                            tags$div(style = "width: 12px; height: 12px; background-color: #F0E442;"), "Mixed results")
)

# Combine the Sankey diagram and legend
sankey <- tagList(
  sankey,
  tags$div(style = "margin-top: -80px;", legend)  # Adjust vertical position of the legend

)

# Display the combined diagram with the legend
sankey
Positive association
Negative association
Mixed results