I'm a Designer just starting to fool around with some d3 tutorials and of course I just got stuck at some point. I was wondering which is the best way to highlight the biggest and smaller columns in a bar graph. I would like them to differ in colour, like "red" for the smaller "green" for the biggest. Anyone can help me out.
This is what i got so far:
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var t = 1297110663, // start time (seconds since epoch)
      v = 70, // start value (subscribers)
      data = d3.range(30).map(next); // starting dataset
  function next() {
    return {
      time: ++t,
      value: v = ~~Math.max(10, Math.min(90, v + 10 * (Math.random() - .5)))
    };
 }
setInterval(function() {
   data.shift();
   data.push(next());
   redraw();
}, 1500);
 var w = 11,
       h = 120;
 var x = d3.scale.linear()
      .domain([0, 1])
      .range([0, w]);
 var y = d3.scale.linear()
     .domain([0, 100])
     .range([0, h]);
 var chart = d3.select("body").append("svg")
     .attr("width", w * (data.length +3))
     .attr("height", h);
 chart.selectAll("rect")
     .data(data)
   .enter().append("rect")
     .attr("x", function(d, i) { return x(i) ; })
     .attr("y", function(d) { return h - y(d.value) - .5; })
     .attr("width", w)
     .attr("height", function(d) { return y(d.value); })
     .style("fill", "#ccc")
     .style("stroke", "white")
chart.select("rect")
    .style("fill", "red");
 chart.append("line")
     .attr("x1", 0)
     .attr("x2", w * (data.length))
     .attr("y1", h - .5)
     .attr("y2", h - .5)
     .style("stroke", "black");
</script>
Many Thanks in advance
You can use:
d3.max(data, function(d) { return d.value; });
along with the corresponding d3.min function to get your extent (there is also d3.extent which returns [min, max]).
Then you could say:
chart.select("rect")
  .filter(function(d) { return d.value === max; })
  .classed("max", true);
which will add the max class to any bar with the maximum value. Do the same for min and you're good.
Also you should be saving your selections like:
var bars = chart.selectAll("rect")
  .data(data);
//use later, like
bars.enter()...
bars.filter()...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With