Groups and axes
Back to table of contents
var dataArray = [5, 20, 40, 50, 60];
var width = 500;
var height = 500;
var max_input = d3.max(dataArray);
// initiate tool to relate dataArray with canvas specifications.
var widthScale = 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
.range([0, width]);
var color = d3.scale.linear()
.domain([0, max_input])
.range(["yellow", "red"]);
/*
generate axis for labeling based on the values of widthScale
*/
var axis = d3.svg.axis()
// override the default number of ticks from 10 to 5
// https://github.com/mbostock/d3/wiki/SVG-Axes
.ticks("5")
.scale(widthScale);
var canvas = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height)
// add ability to group svg elements together.
.append("g")
// shift canvas to a little to the right x increase to 20
.attr("transform", "translate(20, 0)")
canvas.append("g")
// shift this new element to a little to the bottom y increase to (500-20)
// translate(x,y)
.attr("transform", "translate(0, " + (height - 20) + ")")
// new element is based on the axis
.call(axis);
var bars = canvas.selectAll("rect")
.data(dataArray)
.enter()
.append("rect")
// bar's width attribute is based on the value of the widthScale applied dataArray
.attr("width", function(d){ return widthScale(d); } )
.attr("height", 50)
// bar's color attribute is based on the value of the dataArray and the color scale.
.attr("fill", function(d){ return color(d); } )
.attr("y", function(d, i){ return i * 100; } );