Search code examples
javascriptd3.jscolorsradar-chart

d3.js Color Groups for Radar Chart


I'm using this d3 Radar Chart, and now I want to color the groups.

Here's my data -

var data = [
  [
     {axis:"volume(N)",value:0.074095419,group:"one"},
     {axis:"heightBBOX(N)",value:0.618900916,group:"one"},
     {axis:"floor_area(N)",value:0.239036487,group:"one"},
     {axis:"RatioSunExp_TotWall",value:0.670908597,group:"one"
  }],
  [
     {axis:"volume(N)",value:0.373966243,group:"two"},
     {axis:"heightBBOX(N)",value:0.418068276,group:"two"},
     {axis:"floor_area(N)",value:0.039064467,group:"two"},
     {axis:"RatioSunExp_TotWall",value:0.341108011,group:"two"
  }],
  [
     {axis:"volume(N)",value:0.675991163,group:"two"},
     {axis:"heightBBOX(N)",value:0.815015265,group:"two"},
     {axis:"floor_area(N)",value:0.94061374,group:"two"},
     {axis:"RatioSunExp_TotWall",value:0.974062924,group:"two"
  }],
  [
     {axis:"volume(N)",value:0.875950233,group:"two"},
     {axis:"heightBBOX(N)",value:0.210852068,group:"two"},
     {axis:"floor_area(N)",value:0.540645865,group:"two"},
     {axis:"RatioSunExp_TotWall",value:0.074841546,group:"two"
  }]]

and these are my color options

    var color = d3.scale.ordinal()
        .domain(["one","two"])
        .range(["#CC333F","#53e87d"]);

I want to color the group one with a specific color and the group two with another color. How can i do?

update: when I use the code below, all the charts are yellow. So I know that the group is undefined. How can I fix this ?

color: function(d){
    if(d.group == "one"){
        return "red";
        }
    if(d.group == "two"){
        return "green";
        }
    else{
        return "yellow";
    }
    }

Solution

  • The problem with your code is that in radarChartOptions this...

    color: function(d){
    

    ... doesn't retrieve the datum bound to each element.

    The best solution here is looking at the plugin, or emailing its author, to find out how he/she is passing the options. As I don't have time to check the plugin documentation, here is a simple solution, which paints the paths/circles after they are rendered:

    d3.selectAll(".radarArea").each(function(d){
      d3.select(this).style("fill", color(d[0].group))
    });
    
    d3.selectAll(".radarStroke").each(function(d){
      d3.select(this).style("stroke", color(d[0].group))
    });
    
    d3.selectAll(".radarCircle").each(function(d){
      d3.select(this).style("fill", color(d.group))
    });
    

    Here is the updated fiddle: https://jsfiddle.net/1j59znu9/