使用networkd3软件包中的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)
我想通过以下方式自定义结果图:
我想将标签“ Cu in过时的电视”移到其对应节点的框的左侧。
我想将包装盒的宽度加倍以便重复使用。
答案 0 :(得分:0)
使用networkD3
的内置选项无法实现所需的自定义,但是可以通过在加载自定义JavaScript时使用htmlwidgets onRender()
来实现自定义。例如((还增加了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);
}
'
)