如何从D3.js强制布局中的json数据链接额外的属性? [英] How to link extra attributes from json data in a D3.js force layout?

查看:364
本文介绍了如何从D3.js强制布局中的json数据链接额外的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我按照从数据属性中使用FDL和着色节点。还包括工具提示。


I have followed the various examples from Mike Bostock to create a collapsible force layout with directed paths and images at the nodes (related to this other question).

Now, I want to link some extra information to some of the nodes if they contain any extra information, as structured by the data in a json string.

The json string that looks like this:

 {
   "name": "Somename",
   "text": "Some text",
   "extradata": [
            {
              "type": "sometype",
              "icon": "someicon.png"
            },
            {
               "type": "sometype02",
              "icon":  "someicon.png"
            }
   ],
   "children": [
    {
        "name": "Somename",
        "text": "Some text",
        "extradata": [
            {
              "type": "sometype",
              "icon": "someicon.png"
            },
        ]
    },
    {
        "name": "Somename",
        "text": "Some text",
        "extradata": [
            {
              "type": "sometype",
              "icon": "someicon.png"
            },
            { .... },
            { .... },
            { .... },
            ....
        ],
        "children": [
        {
            ....
        }
    },
    ........

In short, I would like to display some of the values of the extradata[] array linked to every node that this extradata attribute. The end result would look something like the image below, where the blue circles represent the contents from extradata (e.g sometype or sometype02).

I'm having trouble understanding how to parse the json string in order to get to those values, and how to create the links to the nodes where they belong.

解决方案

The beauty of d3 is that the Javascript objects are intrinsically linked to the DOM objects that represent them. You might even say the data drives the document.

Presumably you have something like this:

var node = svg.selectAll(".node")
    .data(data.nodes)
    .enter().append("circle")
    [...]

Maybe you want to color each node according to the first datatype property in the JSON:

var node = svg.selectAll(".node")
    .data(data.nodes)
    .enter()
    .append("circle")
    .style("fill", function(d) { 
        return d.extradata[0].type === "sometype" ? "#FF0000" : "#0000FF";
    })

Point is, you already have access to the object in the d variable passed to the function.

Here's an example of using the FDL and coloring nodes from a data property. Also includes tooltips.

这篇关于如何从D3.js强制布局中的json数据链接额外的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆