++++++++++++++++++
更新: 我认为我的问题的答案是你不能插入换行符。一位同事向我指出节点标签是 SVG block ,不支持换行符。
++++++++++++++++++
如何在使用 networkD3 R 包生成的 sankey 图的节点标签中添加换行符?
借用Place text values to right of sankey diagram的例子我可以向标签添加值:
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 太生锈了,无法在它生成后尝试修复它。
最佳答案
您可以将 SVG 文本元素替换为 <foreignObject>
文本/html block 。这个例子需要大量额外的格式/定位才能有用,但它表明这是可能的......
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; })
}
'
)
关于r - 在networkD3桑基图中的节点标签中放置换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44700596/