user3700389
user3700389

Reputation: 300

D3 Change color and scale based on radio button

i am trying to figure out how to make my viz change upon a radio button. I have this radio button:

<div>
        <input type="radio" name="dataset" value="sum_clients" checked> Clients 
        <input type="radio" name="dataset" value="sum_vendors"> Vendors

</div>

...

and the following script:

var color = d3.scale.linear()
        .domain ([0, 1, 2, 100, 1000, 10000, 100000, 1000000, 1758668])
        .range (["white", "#cce0ff", "#b3d1ff", "#80b3ff", "#66a3ff", "#4d94ff", "#1a75ff", "#005ce6", "#003d99"]);


features.selectAll("path")
        .data(topojson.feature(geodata,geodata.objects.collection).features) 
        .enter()
        .append("path")
        .attr("d",path)
        .style("fill", function(d){return color(d.properties.sum_clients); })
        .style("stroke", "#837E7C")
        .on('mouseover', tip.show)
        .on('mouseout', tip.hide)

What i am trying to achieve is to make the color part in style change from color(d.properties.sum_clients) to color(d.properties.sum_vendors) when the radio button changes.

I also need the range of the color function to change (i have a totally different scale of colors for vendors)

I tried some on change functions to get the value of the radio button, but i never managed to make anything work.

Any help is highly appreciated. Thanks

Upvotes: 2

Views: 1024

Answers (1)

Cyril Cherian
Cyril Cherian

Reputation: 32327

First make another color scale for vendors (I have a totally different scale of colors for vendors):

var color = d3.scale.linear()
        .domain ([0, 1, 2, 100, 1000, 10000, 100000, 1000000, 1758668])
        .range (["white", "#cce0ff", "#b3d1ff", "#80b3ff", "#66a3ff", "#4d94ff", "#1a75ff", "#005ce6", "#003d99"]);

var vendorcolor = d3.scale.linear()
        .domain ([0, 1, 2, 100, 1000, 10000, 100000, 1000000, 1758668])
        .range (["white", "red", "green", "blue", "black", "yellow", "purple", "indigo", "violet"]);

Now in your style fill for path do it like this:

features.selectAll("path")
      .data(topojson.feature(geodata,geodata.objects.collection).features) 
        .enter()
        .append("path")
        .attr("d",path)
        .style("fill", function(d){
                   //get the value of the checked
                   var value = d3.select('input[name="dataset"]:checked').node().value;
                   if(value =="sum_vendors"){
                      return vendorcolor(d.properties.sum_vendors);
                   } else {
                      return color(d.properties.sum_clients); 
                   }
       })
        .style("stroke", "#837E7C")
        .on('mouseover', tip.show)
        .on('mouseout', tip.hide)

Upvotes: 2

Related Questions