javascript - d3.js force directed interactive coloring for groups -


i'm working this example of d3.js force-directed graph. example colors nodes according group membership 1 set of groups. have working fine data. however, data can grouped on multiple node attributes (e.g. gender or party affiliation). simple solution make separate graphs, each colored according different attribute.

is there way have color scheme interactive (rather hard coded)? d3 let me add drop down or button pick attribute (gender, affiliation...) used color nodes? this code lets user interactively filter data using drop down menu, i'm not sure how might go interactively picking attributes use colors.

you need

  1. build colour scales , functions attributes you'd want colour on
  2. use them generate select element appropriate options
  3. then call small routine recolours nodes

https://jsfiddle.net/vbpqn1e6/

this miserables example such stuff, tidied bit / lot shows principle:

var groupcolor = d3.scaleordinal(d3.schemecategory20); var namecolor = d3.scalelinear().domain([65,78,90]).range(["#f00", "#0f0", "#00f"]); var madamecolor = d3.scalelinear().domain([true, false]).range(["#f00", "#aaa"]);  var colfuncs = {     "group": function (d) { return groupcolor (d.group); },     "name": function (d) { return namecolor (d.id.substring(0,1).touppercase().charcodeat(0)); },     "madame?": function(d) { return madamecolor (d.id.substring(0,2) === "mm"); } }; var currentcolfunc = colfuncs["group"];  d3.select("body").insert("select", ":first-child")   .on ("change", function() {       var e = d3.event;       if (e) {         currentcolfunc = colfuncs[e.target.value];         updatecolour();       }   })     .selectall("option")     .data(d3.keys(colfuncs))   .enter()   .append("option")   .attr("value", function(d) { return d; })   .text (function(d) { return d; })  ; 

the .on("change") event listens select element , when option chosen uses option's value set current colour scheme (currentcolfunc). if want more choices add more colfuncs object.

this used in updatecolour:

   function updatecolour () {     node.attr("fill", function(d) {          return currentcolfunc(d);      });    }   

Comments