javascript - 使用 d3.js 的 Sankey 图 - 将信息添加到链接标题

标签 javascript html d3.js sankey-diagram

我正在尝试实现这个 sankey 示例:http://bl.ocks.org/d3noob/c9b90689c1438f57d649

它使用 CSV 文件输入字段的数据:

source - target - value

链接标题显示为:enter image description here

我想在数据输入中添加另一个字段:

source - target - value - information

应该添加到链接标题中,如下所示: enter image description here

您看到添加此信息的方法了吗?我尝试更改:

<!-- language: lang-js -->

// load the data (using the timelyportfolio csv method)
d3.csv("sankey.csv", function(error, data) {

//set up graph in same style as original example but empty
graph = {"nodes" : [], "links" : []};

data.forEach(function (d) {
  graph.nodes.push({ "name": d.source });
  graph.nodes.push({ "name": d.target });
  graph.links.push({ "source": d.source,
                     "target": d.target,
                     "value": +d.value,
                     **"information": +d.information**} });
 });

// add the link titles
link.append("title")
    .text(function(d) {
        return d.source.name + " → " + 
            d.target.name + "\n" + format(d.value) + **d.information**; });

不幸的是,这是行不通的。

最佳答案

您没有确切地告诉我们如何它不起作用。所以,我猜问题出在与字符串一起使用的一元加号运算符……如果我的假设是正确的,您可能会在标题中看到 NaN

无论如何,这些是步骤:

首先,在 CSV 中添加字段:

source,target,value,info
Barry,Elvis,2,foo
Frodo,Elvis,2,bar
Frodo,Sarah,2,baz
Barry,Alice,2,foobar
Elvis,Sarah,2,foobaz
Elvis,Alice,2,barbar
Sarah,Alice,4,barbaz

然后,将属性推送到链接中,没有一元加号:

data.forEach(function(d) {
    graph.nodes.push({
        "name": d.source
    });
    graph.nodes.push({
        "name": d.target
    });
    graph.links.push({
        "source": d.source,
        "target": d.target,
        "value": +d.value,
        "information": d.info
    });
});

最后获取title中的属性:

link.append("title")
    .text(function(d) {
        return d.source.name + " → " +
            d.target.name + "\n" + format(d.value) + ", Information: " + d.information
    });

这是更新的 bl.ocks:http://bl.ocks.org/anonymous/5652b4a53cd73f0b3a493b400ec4e1b3/2cdf75a83dc79946722f975144c0ce892836a15a

关于javascript - 使用 d3.js 的 Sankey 图 - 将信息添加到链接标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46904134/

相关文章:

javascript - 为 zepto.js 重写一个插件

javascript - JQuery FullCalendar 从 ajax 成功调用 rerenderEvents 时出现问题

javascript - gojs 中悬停按钮的自定义样式

javascript - 在 HTML 中查找评论

javascript - 类型错误 : Cannot read property 'push' of undefined D3?

javascript - SVG 太小,不包括刻度线和附加文本 d3.js

javascript - 使用 Leaflet 在 basemap 之上创建一个固定的矩形层

javascript - 从用户指定的文件名在 Javascript 中打开文件

javascript - 在包装元素中呈现更新的数据

javascript - 如何根据当前域更改div的样式