[英]Put line break in node labels in networkD3 sankey diagram
++++++++++++++++
更新:我认为我的问题的答案是你不能放入换行符。一位同事向我指出节点标签是SVG块,它不支持换行符。
++++++++++++++++
如何为使用networkD3 R软件包生成的sankey图的节点标签添加换行符?
借用将文本值放置到sankey图右侧的示例,我可以为标签添加值:
library(networkD3)
library(data.table)
set.seed(1999)
links <- data.table(
src = rep(0:4, times=c(1,1,2,3,5)),
target = sample(1:11, 12, TRUE),
value = sample(100, 12)
)[src < target, ] # no loops
nodes <- data.table(name=LETTERS[1:12])
#### Need to hover to get counts
##sankeyNetwork(Links=links, Nodes=nodes, Source='src', Target='target',
## Value='value', NodeID='name', fontSize=16)
## Add text to label
txt <- links[, .(total = sum(value)), by=c('target')]
nodes[txt$target+1L, name := paste0(name, ' (', txt$total, ')')]
## Displays the counts as part of the labels
sankeyNetwork(Links=links, Nodes=nodes, Source='src', Target='target',
Value='value', NodeID='name', fontSize=16, width=600, height=300)
我希望我可以天真地调整paste0
以包含换行符,例如:
name := paste0(name, "\n ", txt$total)
要么
name := paste0(name, "<br/> ", txt$total)
但是我无法使用任何东西,而且我的JavaScript太生锈了,一旦生成就无法尝试修复它。
您可以使用text / html的<foreignObject>
块替换SVG文本元素。 这个例子需要大量额外的格式/定位才有用,但它证明了它有可能......
library(networkD3)
library(htmlwidgets)
library(data.table)
set.seed(1999)
links <- data.table(
src = rep(0:4, times=c(1,1,2,3,5)),
target = sample(1:11, 12, TRUE),
value = sample(100, 12)
)[src < target, ] # no loops
nodes <- data.table(name=LETTERS[1:12])
## Add text to label
txt <- links[, .(total = sum(value)), by=c('target')]
nodes[txt$target+1L, name := paste0(name, '<br>(', txt$total, ')')]
## Displays the counts as part of the labels
sn <- sankeyNetwork(Links=links, Nodes=nodes, Source='src', Target='target',
Value='value', NodeID='name', fontSize=16, width=600, height=300)
onRender(sn,
'
function(el,x) {
d3.selectAll(".node text").remove()
d3.selectAll(".node")
.append("foreignObject")
.attr("width", 100)
.attr("height", 50)
.html(function(d) { return d.name; })
}
'
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.