首页 > 解决方案 > d3.js,我想知道如何根据网络图的节点将此代码颜色

问题描述

从 .json 文件中,我想绘制网络图。

特别是,我想为特定节点赋予不同的颜色,例如 .json 文件中的红色、蓝色。

.json 文件格式

{
  "nodes": [
    {"id": "Myriel", "group": 1},
    {"id": "Napoleon", "group": 1}
  ],
  "links" : [
    {"source": "Napoleon", "target": "Myriel", "value": 1}
  ]
}

我试图为选定的节点着色。所以,我添加了这样的代码:

.style("fill", function(d){
d.color = color(d.name('Myriel'));
return d.color;})

如果不添加此代码,它可以工作。

<!DOCTYPE html>
<meta charset="utf-8">
<style>

    .links line {
        stroke: #aaa;
    }

    .nodes circle {
        pointer-events: all;
        stroke: none;
        stroke-width: 40px;
    }

</style>
<svg width="960" height="600"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>

    var svg = d3.select("svg"),
        width = +svg.attr("width"),
        height = +svg.attr("height");

    var simulation = d3.forceSimulation()
        .force("link", d3.forceLink().id(function(d) { return d.id; }))
        .force("charge", d3.forceManyBody())
        .force("center", d3.forceCenter(width / 2, height / 2));

    d3.json("miserables.json", function(error, graph) {
        if (error) throw error;

        var link = svg.append("g")
            .attr("class", "links")
            .selectAll("line")
            .data(graph.links)
            .enter().append("line");

        myCategory3("Myriel");

        var node = svg.append("g")
            .attr("class", "nodes")
            .selectAll("circle")
            .data(graph.nodes)
            .enter().append("circle")

            .style("fill", function(d){
                d.color = color(d.name('Myriel'));
                return d.color;})

            .attr("r", 2.5)
            .call(d3.drag()
                .on("start", dragstarted)
                .on("drag", dragged)
                .on("end", dragended));

        node.append("title")
            .text(function(d) { return d.id; });

        simulation
            .nodes(graph.nodes)
            .on("tick", ticked);

        simulation.force("link")
            .links(graph.links);

        function ticked() {
            link
                .attr("x1", function(d) { return d.source.x; })
                .attr("y1", function(d) { return d.source.y; })
                .attr("x2", function(d) { return d.target.x; })
                .attr("y2", function(d) { return d.target.y; });

            node
                .attr("cx", function(d) { return d.x; })
                .attr("cy", function(d) { return d.y; });

        }
    });

    function dragstarted(d) {
        if (!d3.event.active) simulation.alphaTarget(0.3).restart();
        d.fx = d.x;
        d.fy = d.y;
    }

    function dragged(d) {
        d.fx = d3.event.x;
        d.fy = d3.event.y;
    }

    function dragended(d) {
        if (!d3.event.active) simulation.alphaTarget(0);
        d.fx = null;
        d.fy = null;
    }

</script>

任何知道如何添加颜色选择节点的人,请帮助我,谢谢。

标签: d3.js

解决方案


推荐阅读