在 R 中自定义桑基图

Customize sankey diagram in R

使用包 中的 sankeyNetwork(),我想稍微自定义生成的图表。可重现的代码如下:

library(networkD3)

links <- data.frame(source = c(0, 0, 0, 0, 0, 2, 2, 3, 3), target = c(1, 2, 3, 4, 5, 6, 7, 6, 7), value = c(70, 56.4, 48.7, 0.9, 338.8, 50.8, 5.6, 47.3, 1.4))
nodes <- data.frame(name = c("Cu in obsolete TVs", "Illegal export", " Domestic recycling", "Open burning", "Dumping landfill", "Reuse", "Material recovery", "Material loss"))

sankeyNetwork(Links=links, Nodes=nodes, Source='source', Target='target',
          Value='value', NodeID='name', fontSize=16, sinksRight = FALSE)

我想通过以下方式自定义结果图:

  1. 我想将标签 "Cu in obsolete TVs" 移动到其对应节点的框左侧。

  2. 我想把盒子的宽度加倍以便重复使用。

您想要的定制无法使用 networkD3 的内置选项实现,但您可以通过使用 onRender() 到 运行 定制 JavaScript 加载时。例如(还增加了 sankeyNetwork() 函数中的右边距,因此左对齐标签不会被截断):

library(networkD3)
library(htmlwidgets)

links <- data.frame(source = c(0, 0, 0, 0, 0, 2, 2, 3, 3), target = c(1, 2, 3, 4, 5, 6, 7, 6, 7), value = c(70, 56.4, 48.7, 0.9, 338.8, 50.8, 5.6, 47.3, 1.4))
nodes <- data.frame(name = c("Cu in obsolete TVs", "Illegal export", " Domestic recycling", "Open burning", "Dumping landfill", "Reuse", "Material recovery", "Material loss"))
sn <- sankeyNetwork(Links=links, Nodes=nodes, Source='source', Target='target',
              Value='value', NodeID='name', fontSize=16, sinksRight = FALSE, 
              margin = list(right = 150))

onRender(sn,
  '
  function(el,x) {
    d3.select(el)
      .selectAll(".node text")
      .filter(function(d) { return d.name == "Cu in obsolete TVs"; })
      .attr("x", x.options.nodeWidth - 16)
      .attr("text-anchor", "end");

    d3
      .selectAll("rect")
      .filter(function (d, i) { return i === 5;})
      .attr("width", x.options.nodeWidth * 2);
  }
  '
)