R-networkD3-sankeyNetwork-链接值标签千位分隔符

时间:2019-04-08 16:09:59

标签: r sankey-diagram htmlwidgets networkd3

我正在使用中的sankeyNetwork。在绘制数据时,如果将鼠标悬停在sankey链接上,则会显示链接标签,并且该标签中的千位分隔符是逗号。我希望这一点。

这里是一个例子:

library(networkD3)

nodes <- data.frame(name = c('a','b'))
links <- data.frame(source = c(0), target = c(1), value = c(12000))

p <- sankeyNetwork(
  Links = links,
  Source = "source",
  Target = "target",
  Value = "value",
  Nodes = nodes,
  NodeID = "name",
  fontSize = 12,
  nodeWidth = 30,
  iterations = 0
)

p

output

谢谢!

Xevi

1 个答案:

答案 0 :(得分:0)

您可以通过使用htmlwidgets::onRender ...重写链接标题来实现此目的...

library(networkD3)
library(htmlwidgets)

nodes <- data.frame(name = c('a','b'))
links <- data.frame(source = c(0), target = c(1), value = c(12000))

p <- sankeyNetwork(
  Links = links,
  Source = "source",
  Target = "target",
  Value = "value",
  Nodes = nodes,
  NodeID = "name",
  fontSize = 12,
  nodeWidth = 30,
  iterations = 0
)

customJS <- '
function(el,x) { 
    var link = d3.selectAll(".link");

    var format = d3.formatLocale({"decimal": ",", "thousands": ".", "grouping": [3], "currency": ["", "\u00a0€"]}).format(",.0f");

    link.select("title").select("body")
        .html(function(d) { return "<pre>" + d.source.name + " \u2192 " + d.target.name +
            "\\n" + format(d.value) + "<pre>"; });
}
'
onRender(p, customJS)

enter image description here