使用JSON更改链接的颜色

时间:2016-10-29 12:35:34

标签: javascript json d3.js

在这段代码中,我想改变链接的颜色但是有问题。这是在运行时创建的JSON文件。

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="D3js_edges_connected_by_nodes_id.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script type="text/javascript" src="http://d3js.org/d3.v2.min.js"></script>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
    <title>Weighted Citation Graph</title>
    <style>
        path.link {
            fill: none;
            stroke: #666;
            stroke-width: 1.5px;
        }

        circle {
            fill: #ccc;
            stroke: #333;
            stroke-width: 1.5px;
        }

        text {
            font: 10px sans-serif;
            pointer-events: none;
        }

            text.shadow {
                stroke: #fff;
                stroke-width: 3px;
                stroke-opacity: .8;
            }

        body {
            background-color: white;
            margin: 0px;
        }

        .graphContainer {
            text-shadow: -1px -1px 0 white, 1px -1px 0 white, -1px 1px 0 white, 1px 1px 0 white;
        }
    </style>
    <script>
        function load_graph(text) {

            var color = d3.scale.category20();
            try{
                var data = JSON.parse(text);
            } catch (e) {
                window.alert("sometext: "+e);
            }

            //var data1 = {
            //    "nodes": [
            //        { "id": 0, "name": "paper1", "citation": 5, "group": 1 },
            //        { "id": 1, "name": "paper2", "citation": 8, "group": 2 },
            //        { "id": 2, "name": "paper3", "citation": 12, "group": 3 },
            //        { "id": 3, "name": "paper4", "citation": 25, "group": 4 },
            //        { "id": 4, "name": "paper5", "citation": 15, "group": 5 },
            //        { "id": 5, "name": "paper6", "citation": 5, "group": 1 },
            //        { "id": 6, "name": "paper7", "citation": 8, "group": 2 },
            //        { "id": 7, "name": "paper8", "citation": 12, "group": 3 },
            //        { "id": 8, "name": "paper9", "citation": 25, "group": 4 },
            //        { "id": 9, "name": "paper10", "citation": 15, "group": 5 }
            //    ],
            //    "links": [
            //        { "source": 0, "target": 1, "name": "A-B-1", "value": 8 },
            //        { "source": 0, "target": 1, "name": "A-B-2", "value": 24 },
            //        { "source": 0, "target": 2, "name": "A-C-1", "value": 12 },
            //        { "source": 0, "target": 2, "name": "A-C-3", "value": 44 },
            //        { "source": 2, "target": 3, "name": "A-D-1", "value": 11 },
            //        { "source": 2, "target": 3, "name": "A-D-2", "value": 35 },
            //        { "source": 2, "target": 4, "name": "A-E-1", "value": 16 },
            //        { "source": 2, "target": 4, "name": "A-E-5", "value": 30 },
            //        { "source": 4, "target": 5, "name": "A-B-1", "value": 8 },
            //        { "source": 4, "target": 5, "name": "A-B-2", "value": 24 },
            //        { "source": 5, "target": 6, "name": "A-C-1", "value": 12 },
            //        { "source": 5, "target": 6, "name": "A-C-3", "value": 44 },
            //        { "source": 5, "target": 7, "name": "A-D-1", "value": 11 },
            //        { "source": 5, "target": 7, "name": "A-D-2", "value": 35 },
            //        { "source": 7, "target": 8, "name": "A-E-1", "value": 16 },
            //        { "source": 7, "target": 8, "name": "A-E-5", "value": 30 },
            //        { "source": 8, "target": 3, "name": "A-C-1", "value": 12 },
            //        { "source": 8, "target": 3, "name": "A-C-3", "value": 44 },
            //        { "source": 8, "target": 9, "name": "A-D-1", "value": 11 },
            //        { "source": 8, "target": 9, "name": "A-D-2", "value": 35 }
            //    ]
            //};
            //var data = {
            //    "nodes": [{
            //        "id": 124587,
            //        "name": "paper1",
            //        "citation": 5,
            //        "group": 1
            //    }, {
            //        "id": 178456,
            //        "name": "paper2",
            //        "citation": 8,
            //        "group": 2
            //    }, {
            //        "id": 125698,
            //        "name": "paper3",
            //        "citation": 5,
            //        "group": 1
            //    }],
            //    "links": [{
            //        "source": 178456,
            //        "target": 124587,
            //        "name": "A-B-1",
            //        "value": 15
            //    }, {
            //        "source": 124587,
            //        "target": 125698,
            //        "name": "A-B-2",
            //        "value": 30
            //    },
            //    {
            //        "source": 124587,
            //        "target": 125698,
            //        "name": "A-c-1",
            //        "value": 25
            //    }
            //    , {
            //        "source": 124587,
            //        "target": 125698,
            //        "name": "A-c-2",
            //        "value": 45
            //    }]
            //};
            // used to store the number of links between two nodes. 
            // mLinkNum[data.links[i].source + "," + data.links[i].target] = data.links[i].linkindex;
            var mLinkNum = {};

            // sort links first
            // sortLinks();

            data.links.sort(function (a, b) {
                if (a.source > b.source) { return 1; }
                else if (a.source < b.source) { return -1; }
                else {
                    if (a.target > b.target) { return 1; }
                    if (a.target < b.target) { return -1; }
                    else { return 0; }
                }
            })

            // set up linkIndex and linkNumer, because it may possible multiple links share the same source and target node
            setLinkIndexAndNum();


            var w = 2000,
                h = 2000;

            var force = d3.layout.force()
            .size([w, h])
            .linkDistance(200)
            .charge(-600)
            .on("tick", tick);

            var svg = d3.select(".graphContainer").append("svg:svg")
            .attr("width", w)
            .attr("height", h);

            var color = d3.scale.category10()
            var edges = [];
            data.links.forEach(function (e) {
                var sourceNode = data.nodes.filter(function (n) {
                    return n.id === e.source;
                })[0],
                    targetNode = data.nodes.filter(function (n) {
                        return n.id === e.target;
                    })[0];

                edges.push({
                    source: sourceNode,
                    target: targetNode,
                    name: e.name,
                    value: e.value,
                    linkindex: e.linkindex
                });
            });

            console.log(edges)
            force
              .nodes(data.nodes)
              .links(edges)
              .start();

            var path = svg.append("svg:g")
            .selectAll("line")
            .data(edges)
            .enter().append("svg:path")
            .attr("class", "link")
            .style("stroke-width", function (d, i) {
                console.log(d.value)
                return Math.sqrt(d.value);
            }).style('stroke', function (d, i) {
                return color(i);
            });


            var circle = svg.append("svg:g")
            .selectAll("circle")
            .data(force.nodes())
            .enter().append("svg:circle")
            .attr("r", function (d) {
                return ( Math.sqrt(d.citation));
            })
            .style("fill", function (d) {
                return color(d.group);
            })
            .call(force.drag);

            var text = svg.append("svg:g")
            .selectAll("g")
            .data(force.nodes())
            .enter().append("svg:g");
            console.log('test')
            // A copy of the text with a thick white stroke for legibility.
            text.append("svg:text")
              .attr("x", 8)
              .attr("y", ".31em")
              .attr("class", "shadow")
              .text(function (d) {
                  return d.name;
              });

            text.append("svg:text")
              .attr("x", 8)
              .attr("y", ".31em")
              .text(function (d) {
                  return d.name;
              });

            // Use elliptical arc path segments to doubly-encode directionality.
            function tick() {
                path.attr("d", function (d, i) {
                    var dx = d.target.x - d.source.x,
                       dy = d.target.y - d.source.y,
                       dr = 75 * d.linkindex;  //linknum is defined above
                    var output = "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + d.target.x + "," + d.target.y;
                    //console.log(d)
                    return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + d.target.x + "," + d.target.y;
                });

                // Add tooltip to the connection path
                path.append("svg:title")
                  .text(function (d, i) {
                      return d.name;
                  });

                circle.attr("transform", function (d) {
                    return "translate(" + d.x + "," + d.y + ")";
                });

                text.attr("transform", function (d) {
                    return "translate(" + d.x + "," + d.y + ")";
                });
            }

            // sort the links by source, then target
            function sortLinks1() {
                data.links.sort(function (a, b) {
                    if (a.source > b.source) {
                        return 1;
                    } else if (a.source < b.source) {
                        return -1;
                    } else {
                        if (a.target > b.target) {
                            return 1;
                        }
                        if (a.target < b.target) {
                            return -1;
                        } else {
                            return 0;
                        }
                    }
                });
            }



            //any links with duplicate source and target get an incremented 'linknum'
            function setLinkIndexAndNum1() {
                for (var i = 0; i < data.links.length; i++) {
                    if (i != 0 &&
                        data.links[i].source == data.links[i - 1].source &&
                        data.links[i].target == data.links[i - 1].target) {
                        data.links[i].linkindex = data.links[i - 1].linkindex + 1;
                        console.log(data.links[i].linkindex)
                    } else {
                        data.links[i].linkindex = 1;
                        console.log(data.links[i].linkindex)
                    }
                    // save the total number of links between two nodes
                    if (mLinkNum[data.links[i].target + "," + data.links[i].source] !== undefined) {
                        mLinkNum[data.links[i].target + "," + data.links[i].source] = data.links[i].linkindex;
                    } else {
                        mLinkNum[data.links[i].source + "," + data.links[i].target] = data.links[i].linkindex;
                    }
                }
            }

            function setLinkIndexAndNum() {

                for (var i = 0; i < data.links.length; i++) {
                    if (i != 0 &&
                        data.links[i].source == data.links[i - 1].source &&
                        data.links[i].target == data.links[i - 1].target) {
                        data.links[i].linkindex = data.links[i - 1].linkindex + 1;
                    }
                    else {
                        data.links[i].linkindex = 1;

                    };
                };

            }



        }

    </script>
</head>
<body>
     <form id="form1" runat="server">
    <div>
    <script src="//d3js.org/d3.v3.min.js"></script>
        <textarea runat="server" id="textarea" cols="80" rows="20"></textarea>
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    </div>
        <div id="graphContainer" class="graphContainer"></div>
    </form>
</body>
</html>

我正在努力解决这个问题,而且我已经采用了很多方法来改变它,但我没有做对。

1 个答案:

答案 0 :(得分:0)

根据绑定数据中g的值着色每个链接:

.style('stroke', function (d) {
    return color(d.g);
});

然而,检查您的edges数组,我可以看到没有名为g的键。您必须将其推送到edges(假设g中存在data):

edges.push({
    source: sourceNode,
    target: targetNode,
    name: e.name,
    value: e.value,
    linkindex: e.linkindex,
    g: e.g//push the value of g
});