将文本值放在桑基图的右侧

Place text values to right of sankey diagram

在使用 networkD3 呈现的桑基图上放置文本是否有技巧?我想让端点的值显示为框右侧的文本。我意识到将鼠标悬停在框上会显示值,但随着框变小,如果值始终在侧面可见,在许多情况下描绘信息会容易得多。

这是一个例子;我可以通过将值添加为标签的一部分来破解它,但将值显示在图表右侧会更好。

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)

抱歉,我刚刚 运行 穿过这个。这对于 htmlwidgets 中的新 onRender 函数非常有用。我试图内联评论以解释添加的几行 JavaScript 以移动节点文本。 networkD3 这些 lines 中的过滤器可根据宽度将位置更改为向右或向左。我们将把它应用到所有文本,所以它会在我们的节点矩形的右边。

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)



#################### move leaf node text right ################
# for this to work
#   install the newest htmlwidgets
#   devtools::install_github("ramnathv/htmlwidgets")

library(htmlwidgets)
#  add margin left since we'll need extra room
#   if you are wondering why margin left,
#   I think we just discovered a bug
sn <- sankeyNetwork(
  Links=links, Nodes=nodes, Source='src', Target='target',
  Value='value', NodeID='name', fontSize=16,
  width=600, height=300,
  # give us so room for our newly aligned labels
  margin = list("left"=100)
)
# see how it looks
sn

# now let's use the new htmlwidget function
#  onRender
onRender(
  sn,
'
function(el,x){
  // select all our node text
  var node_text = d3.select(el)
    .selectAll(".node text")
    //and make them match
    //https://github.com/christophergandrud/networkD3/blob/master/inst/htmlwidgets/sankeyNetwork.js#L180-L181
    .attr("x", 6 + x.options.nodeWidth)
    .attr("text-anchor", "start");
}
'
)