如何在力导向图中改变节点的颜色

时间:2016-06-22 06:11:18

标签: d3.js

我是d3.js的新手。我正在使用力导向图。我制作了图形的3d节点。所有节点都有相同的颜色。我想改变节点的颜色,并想要应用随机颜色。有人能帮助我吗?

这是我的代码:

    var   w = 1000,
      h =  800,
      circleWidth = 5; 


var palette = {
      "lightgray": "#E5E8E8",
      "gray": "#708284",
      "mediumgray": "#536870",
      "blue": "#3B757F"
  }

var colors = d3.scale.category20();

var nodes = [
      { name: "My Skills"},
      { name: "HTML5", target: [0], value: 58 },
      { name: "CSS3", target: [0, 1], value: 65 },  
      { name: ".NET", target: [0, 3], value: 48 }, 
      { name: "Java", target: [0,3,4], value: 40 }, 
      { name: "jQuery", target: [0, 1, 2], value: 52 },
      { name: "Photoshop", target: [0, 1, 2, 8], value: 37 },
      { name: "PHP", target: [0,1,2], value: 20 },
      { name: "Wordpress", target: [0,1,2,3,9], value: 67 },
      { name: "d3", target: [0,1,2,7,8], value: 25 },
      { name: "Angular", target: [0,1,2,7,8], value: 25 },
      { name: "Adobe CS", target: [0,1,2,12], value: 57 },
      { name: "mySql", target: [0,9,10], value: 20 },
];

var links = [];

for (var i = 0; i < nodes.length; i++){
      if (nodes[i].target !== undefined) { 
            for ( var x = 0; x < nodes[i].target.length; x++ ) 
              links.push({
                  source: nodes[i],
                  target: nodes[nodes[i].target[x]]  
              });
      };
};




var myChart = d3.select('body')
      .append("div")
        .classed("svg-container", true)

      .append('svg')
        .attr("preserveAspectRatio", "xMinYMin meet")
        .attr("viewBox", "0 0 1000 800")
        .classed("svg-content-responsive", true)


var force = d3.layout.force()
      .nodes(nodes)
      .links([])
      .gravity(0.1)
      .charge(-1000)
      .size([w,h]); 





      var link = myChart.selectAll('line') 
            .data(links).enter().append('line')
            .attr('stroke', palette.lightgray)
            .attr('strokewidth', '1');

      var node =  myChart.selectAll('circle')  
            .data(nodes).enter() 
            .append('g') 
            .call(force.drag); 
var grads = myChart.append("defs").selectAll("radialGradient")
    .data(nodes)
   .enter()
    .append("radialGradient")
    .attr("gradientUnits", "objectBoundingBox")
    .attr("cx","20%")
    .attr("cy", "30%")
    .attr("r", "100%")
    .attr("id", function(d, i) { return "grad" + i; });

grads.append("stop")
    .attr("offset", "0%")
    .style("stop-color", "white");

grads.append("stop")
    .attr("offset", "100%")
    .style("stop-color",  function(d) { return colors(d.cluster); });

     node.append('circle')
            .attr('cx', function(d){return d.x; })
            .attr('cy', function(d){return d.y; })
            .attr('fx', function(d){return d.x; })
            .attr('fy', function(d){return d.y; })
            .attr('r', function(d,i){
                  console.log(d.value);
                  if ( i > 0 ) {
                        return circleWidth + d.value; 
                  } else {
                        return circleWidth + 35; 
                  }
            })

            .attr('fill', function(d,i){
                  if ( i > 0 ) {
              return "url(#grad" + i + ")";

                 } else {
                       return '#fff';
                }
            })
            .attr('strokewidth', function(d,i){
                  if ( i > 0 ) {
                        return '0';
                  } else {
                        return '2';
                  }
            })
            .attr('stroke', function(d,i){
                  if ( i > 0 ) {
                        return '';
                  } else {
                        return 'black';
                  }
            });


      force.on('tick', function(e){ 
            node.attr('transform', function(d, i){
              return 'translate(' + d.x + ','+ d.y + ')'
            })

          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.append('text')
            .text(function(d){ return d.name; })
            .attr('font-family', 'Raleway', 'Helvetica Neue, Helvetica')
            .attr('fill', function(d, i){
              console.log(d.value);
                  if ( i > 0 && d.value < 10 ) {
                        return palette.mediumgray;
                  } else if ( i > 0 && d.value >10 ) {
                        return palette.lightgray;
                  } else {
                        return palette.blue;
                  }
            })
            .attr('text-anchor', function(d, i) {
                  return 'middle';
            })
            .attr('font-size', function(d, i){
                  if (i > 0) {
                        return '.8em';
                  } else {
                        return '.9em';    
                  }
            }) 

force.start();

2 个答案:

答案 0 :(得分:4)

您必须在代码中使用节点索引而不是d.cluster,因为数据数组中没有多个群集。

grads.append("stop")
   .attr("offset", "100%")
   .style("stop-color", function(d,i) {
     return colors(i);
   });

&#13;
&#13;
var w = 1000,
   h = 800,
   circleWidth = 5;


 var palette = {
   "lightgray": "#E5E8E8",
   "gray": "#708284",
   "mediumgray": "#536870",
   "blue": "#3B757F"
 }

 var colors = d3.scale.category20();

 var nodes = [{
   name: "My Skills"
 }, {
   name: "HTML5",
   target: [0],
   value: 58
 }, {
   name: "CSS3",
   target: [0, 1],
   value: 65
 }, {
   name: ".NET",
   target: [0, 3],
   value: 48
 }, {
   name: "Java",
   target: [0, 3, 4],
   value: 40
 }, {
   name: "jQuery",
   target: [0, 1, 2],
   value: 52
 }, {
   name: "Photoshop",
   target: [0, 1, 2, 8],
   value: 37
 }, {
   name: "PHP",
   target: [0, 1, 2],
   value: 20
 }, {
   name: "Wordpress",
   target: [0, 1, 2, 3, 9],
   value: 67
 }, {
   name: "d3",
   target: [0, 1, 2, 7, 8],
   value: 25
 }, {
   name: "Angular",
   target: [0, 1, 2, 7, 8],
   value: 25
 }, {
   name: "Adobe CS",
   target: [0, 1, 2, 12],
   value: 57
 }, {
   name: "mySql",
   target: [0, 9, 10],
   value: 20
 }, ];

 var links = [];

 for (var i = 0; i < nodes.length; i++) {
   if (nodes[i].target !== undefined) {
     for (var x = 0; x < nodes[i].target.length; x++)
       links.push({
         source: nodes[i],
         target: nodes[nodes[i].target[x]]
       });
   };
 };




 var myChart = d3.select('body')
   .append("div")
   .classed("svg-container", true)

 .append('svg')
   .attr("preserveAspectRatio", "xMinYMin meet")
   .attr("viewBox", "0 0 1000 800")
   .classed("svg-content-responsive", true)


 var force = d3.layout.force()
   .nodes(nodes)
   .links([])
   .gravity(0.1)
   .charge(-1000)
   .size([w, h]);





 var link = myChart.selectAll('line')
   .data(links).enter().append('line')
   .attr('stroke', palette.lightgray)
   .attr('strokewidth', '1');

 var node = myChart.selectAll('circle')
   .data(nodes).enter()
   .append('g')
   .call(force.drag);

 var grads = myChart.append("defs").selectAll("radialGradient")
   .data(nodes)
   .enter()
   .append("radialGradient")
   .attr("gradientUnits", "objectBoundingBox")
   .attr("cx", "20%")
   .attr("cy", "30%")
   .attr("r", "100%")
   .attr("id", function(d, i) {
     return "grad" + i;
   });

 grads.append("stop")
   .attr("offset", "0%")
   .style("stop-color", "white");

 grads.append("stop")
   .attr("offset", "100%")
   .style("stop-color", function(d, i) {
     return colors(i);
   });

 node.append('circle')
   .attr('cx', function(d) {
     return d.x;
   })
   .attr('cy', function(d) {
     return d.y;
   })
   .attr('fx', function(d) {
     return d.x;
   })
   .attr('fy', function(d) {
     return d.y;
   })
   .attr('r', function(d, i) {


     if (i > 0) {
       return circleWidth + d.value;
     } else {
       return circleWidth + 35;
     }
   })

 .attr('fill', function(d, i) {
     if (i > 0) {
       return "url(#grad" + i + ")";

     } else {
       return '#fff';
     }
   })
   .attr('strokewidth', function(d, i) {
     if (i > 0) {
       return '0';
     } else {
       return '2';
     }
   })
   .attr('stroke', function(d, i) {
     if (i > 0) {
       return '';
     } else {
       return 'black';
     }
   });


 force.on('tick', function(e) {
   node.attr('transform', function(d, i) {
     return 'translate(' + d.x + ',' + d.y + ')'
   })

   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.append('text')
   .text(function(d) {
     return d.name;
   })
   .attr('font-family', 'Raleway', 'Helvetica Neue, Helvetica')
   .attr('fill', function(d, i) {

     if (i > 0 && d.value < 10) {
       return palette.mediumgray;
     } else if (i > 0 && d.value > 10) {
       return palette.lightgray;
     } else {
       return palette.blue;
     }
   })
   .attr('text-anchor', function(d, i) {
     return 'middle';
   })
   .attr('font-size', function(d, i) {
     if (i > 0) {
       return '.8em';
     } else {
       return '.9em';
     }
   })

 force.start();
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:3)

你可以这样做:

定义色标

var color = d3.scale.category10();

然后在圆圈的填充中执行:

.attr('fill', function(d,i){
                 return color(i);
            })