Loading External Data
Back to table of contents
var width = 500, height = 250, padding = 1;
var canvas = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height)
// Creates a request for the JSON file at the specified url, callback function gets data parameter containing json object.
d3.json("mydata.json", function(data) {
// workaround to get maximum value since our data is multidimensional.
var max_age = d3.max(data, function(d) { return +d.age;} );
var median_age = max_age/2;
/*
Make use of scales, which takes an input range (data) 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.
SEE Scales Tutorial.
*/
var widthScale = d3.scale.linear()
.domain([0, max_age])
.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()
.domain([0, max_age])
.range(["green", "grey"]);
var barHeight = height / data.length;
// each corresponding bar and text should be considered in one group.
var bars = canvas.selectAll("g")
.data(data)
.enter().append("g");
bars.append("rect")
// bar's color is based on the age calculated on color scale.
.attr("fill", function(d){ return color(d.age); } )
// bar's width is based on the age calculated on width scale.
.attr("width", function(d){ return widthScale(d.age); } )
// make use of simple scaling using number of elements in data.
.attr("height", (barHeight - padding) )
// starting position of bar's y axis is based on its index in data array and barheight.
.attr("y", function(d, i){ return i * barHeight; } );
bars.append("text")
.attr("dy",".35em")
.attr("y", function(d, i){ return ((i+1) * barHeight) - (data.length * padding + 1); } )
.attr("x", 0)
.attr("fill", "white")
.text(function(d) { return d.name + " " + d.age; });
});