score:2

Accepted answer

I think this is what you want to achieve, I will leave it to you to manage the color scheme, the thing that you have to manage is the color from [0, 255].

Just add it inside the click event you attached to the bars.

//Width and height
var w = 500;
var h = 100;
var barPadding = 1;

var dataset = [5, 10, 13, 19, 21, 25, 22, 18, 15, 13, 11, 12, 15, 20, 18, 17, 16, 18, 23, 25];

//Create SVG element
var svg = d3.select("body")
       .append("svg")
       .attr("width", w)
       .attr("height", h);

svg.selectAll("rect")
       .data(dataset)
       .enter()
       .append("rect")
       .attr("class", "allbars")
       .attr("x", function (d, i) {
              return i * (w / dataset.length);
       })
       .attr("y", function (d) {
              return h - (d * 4);
       })
       .attr("width", w / dataset.length - barPadding)
       .attr("height", function (d) {
              return d * 4;
       })
       .attr("fill", "#2296F3")
       .on("click", function (d) {
           d3.select("#the_circle circle")
           .attr("fill", function () { return "rgb(0, 0, " + Math.round(d * 10) + ")"; });

          d3.selectAll('.allbars').style('fill', '#2296F3');
          d3.select(this).style("fill", "#012B4E");
        }
       )


// Add circle SVG, give it class circle_data that will be effected by on click
map_svg = d3.select("#the_circle").append("svg")
.attr("class", "svgWrapper")
map_svg.append("circle")
.attr("class", "performer_circle")
.attr("cx",100)
.attr("cy", 100)
.attr("r", 50)
.attr("fill", "black");
body {
  font-size: 19px;
  font-family: 'Open Sans', sans-serif;
  font-weight: 400;
  text-align: center;
}

#title {
  font-size: 20px;
  padding-bottom: 10px;
  padding-top: 20px;
  font-weight: 300;
}
<!DOCTYPE html>
<html lang="en">

<head>
   <meta charset="utf-8">
   <title>D3: Adding dynamic color, based on data</title>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.13/d3.js"></script>
</head>


<body>
 <div id="bars"></div>
 <div id="the_circle"></div>
 <div id="title">Clicking on a bar changes it's color, it also triggers the circle to change colors</div>
</body>
</html>


Related Query