bar chart using scale
by hrabinowitz
JavaScript
// using a scale to figure out the height of bars, and color, too.
//Width and height
var w = 500;
var h = 300;
var barPadding = 1;
var dataset = [ 5, 10, null, null, 21, 25, 22, 18, 15, 13,
11, 12, 15, 20, 18, 17, 16, 18, 23, 25 ];
var padding = 20;
var maxData = d3.max(dataset, function(d) { return d; });
console.log("maxData=", maxData);
var scale = d3.scale.linear()
.domain([0, maxData])
.range([0, h - padding * 2]);
var colorScale = d3.scale.linear()
.domain([0, maxData])
.range(["yellow", "blue"]);
console.log("scale(0)=", colorScale(0), colorScale(25));
// problem is that scale(null) is 0 !
// This would give undesirable values in line graph,
// though for bar graph it is not noticeable.
// Let's try using betterScale.
// Actually that doesn't help. Instead, I used a
// custom radius for the red dots.
console.log("scale(null)=", scale(null));
function betterScale(d) {
if (d == null) {
return null;
}
return scale(d);
}
//Create SVG element
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
svg.append("rect")
.attr("width", "100%")
.attr("height", "100%")
.attr("fill", "beige");
var rects = svg.selectAll("rect.bar")
.data(dataset)
.enter()
.append("rect")
.attr("x", function(d, i) {
return i * (w / dataset.length);
})
.attr("y", function(d) {
return h - padding - betterScale(d); //h - (d * 4);
})
.attr("width", w / dataset.length - barPadding)
.attr("height", function(d) {
return...