Scales part2

Back to table of contents
    var dataArray = [5, 20, 40, 50, 60];
    var width = 500;
    var height = 500;
    var max_input = d3.max(dataArray);
    /*
       Make use of scales, which takes an input range (dataArray) and transform that
       to a range that will fit in the container. ie.. those rectangle width's should
       be no more than the canvas width.
     */
    var widthScale = d3.scale.linear()
                      // A scale's input domain is the range of possible input data values
                      // declaring to the scale function that the lowest possible input is 0
                      // while the maximum possible input is max_input aka 60.
                      .domain([0, max_input])
                      // A scale's output range is the range of possible output values
                      // output would be from the lowest range : 0 to the highest range: width aka 500
                      .range([0, width]);
    /*
      Make use of scales to transform the input array range to its color heat.
      The bigger value the closer to the maximum range.
      This example is perfect for data visualization techniques of light colors (signifying
      low levels) to warmer colors (signifying higher levels).
     */
    var color = d3.scale.linear()
                      // A scale's input domain is the range of possible input data values
                      .domain([0, max_input])
                      // A scale's output range is the range of possible output values
                      // output would be from the lowest range : yellow to the highest range: red
                      .range(["yellow", "red"]);
    var canvas = d3.select("body")
                  .append("svg")
                  .attr("width", width)
                  .attr("height", height);
    /*
      Notice that the width of each bar is the value of each element of the dataArray applied to widthScale
      so:
      1st bar is widthScale(5) which is 41.6
      2nd bar is widthScale(20) which is 166.6
      3rd bar is widthScale(40) which is 333.3
      4th bar is widthScale(50) which is 416.6
      last bar is widthScale(60) which is 500
     */
    var bars = canvas.selectAll("rect")
                  .data(dataArray)
                  .enter()
                  .append("rect")
                  .attr("width", function(d){ return widthScale(d); } )
                  .attr("height", 50)
                  .attr("fill", function(d){ return color(d); } )
                  .attr("y", function(d, i){ return i * 100; } );