R networkD3::sankeyNetwork,如何添加 y 轴标签而不丢失 htmlwidgets::onRender 添加的元素

问题描述 投票:0回答:1

我正在尝试将 y 轴标签添加到我的 sankey 网络中。我设法使用 htmlwidgets::onRender 添加 x 轴标签。我尝试根据此answer添加一些 y 轴标签。然而,我之前的 x 轴标签在添加 y 标签后消失了。如何保留 x 标签?

代码:

library(networkD3)
library(manipulateWidget)
library(htmltools)
library(htmlwidgets)

# prepare data
links <- data.frame(
  source = c("group_A","group_A", "group_B", "group_C", "group_C", "group_E"), 
  target = c("group_C","group_D", "group_E", "group_F", "group_G", "group_H"), 
  value = c(2,3, 2, 3, 1, 3)
)

nodes <- data.frame(
  name = unique(c(as.character(links$source), as.character(links$target)))
)

links$IDsource <- match(links$source, nodes$name) - 1
links$IDtarget <- match(links$target, nodes$name) - 1

# sankey network
sankey = sankeyNetwork(Links = links,
                       Nodes = nodes,
                       Source = "IDsource",
                       Target = "IDtarget",
                       Value = "value",
                       NodeID = "name",
                       fontSize = 20)

# add x-axis labels 
js_string <-
  '
   function(el) {

    var cols_x = this.sankey.nodes()
      .map(d => d.x).filter((v, i, a) => a.indexOf(v) === i)
      .sort(function(a, b){return a - b});

    var labels = ["A", "B", "C" ]

    cols_x.forEach((d, i) => {
      d3.select(el).select("svg")
        .append("text")
        .attr("x", d)
        .attr("y", 12)
        .attr("text-anchor", "start")
        .text(labels[i]);
    })
   }
  '

# original plot
sankey <- onRender(sankey, js_string)
sankey


# try adding y-axis labels
leftTx = tags$div( 
  style="max-width: 30vw; padding-bottom: 15px; height: 100%; display: flex; align-items: center; justify-content: center;", 
  tags$p("This text is on the left side"))
rightTx = tags$p("This text is on the right",
                 style="max-width:30vw")

cS <- combineWidgets(sankey,
                     leftCol = leftTx,
                     rightCol = rightTx)

cS

原图

添加 y 标签后

r sankey-diagram
1个回答
0
投票

您可以在您使用的同一自定义 JavaScript 中向左侧和右侧添加文本...

onRender(sankey, jsCode = '
function(el) {
  var cols_x = this.sankey.nodes()
    .map(d => d.x).filter((v, i, a) => a.indexOf(v) === i)
    .sort(function(a, b){return a - b});

  var labels = ["A", "B", "C" ]

  cols_x.forEach((d, i) => {
    d3.select(el).select("svg")
      .append("text")
      .attr("x", d)
      .attr("y", 12)
      .attr("text-anchor", "start")
      .text(labels[i]);
  })
  
  d3.select(el).select("svg")
      .append("text")
      .attr("x", 0)
      .attr("y", d3.select(el).select("svg").node().clientHeight / 2)
      .attr("text-anchor", "end")
      .text("text on left");
  
  d3.select(el).select("svg")
      .append("text")
      .attr("x", d3.select(el).select("svg").node().clientWidth)
      .attr("y", d3.select(el).select("svg").node().clientHeight / 2)
      .attr("text-anchor", "start")
      .text("text on right");
}
')

© www.soinside.com 2019 - 2024. All rights reserved.