My notes
Edit of mbostock's DRY Bar Chart
A variation of the example bar chart using a slightly more D.R.Y. style. The visual encoding is represented by two functions and their composition:
- The value accessor returns the value (or property) to encode for a given data object.
- The scale maps this value to a visual display encoding, such as a pixel position.
- The map function represents the composition value ○ scale, mapping from data to display.
Inspired by Andrew Winterman’s post, Tooling for the Lazy Programmer: DRYing up D3.
xxxxxxxxxx
<meta charset="utf-8">
<style>
body {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.bar {
fill: steelblue;
}
.x.axis path {
display: none;
}
</style>
<body>
<script src="https://d3js.org/d3.v3.min.js"></script>
<script>
var margin = {top: 20, right: 20, bottom: 30, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var xValue = function(d) { return d.Year; }, // data -> value
xScale = d3.scale.ordinal().rangeRoundBands([0, width], .1), // value -> display
xMap = function(d) { return xScale(xValue(d)); }, // data -> display
xAxis = d3.svg.axis().scale(xScale).orient("bottom");
var yValue = function(d) { return d.DogsEaten; }, // data -> value
yScale = d3.scale.linear().range([height, 0]), // value -> display
yMap = function(d) { return yScale(yValue(d)); }, // data -> display
yAxis = d3.svg.axis().scale(yScale).orient("left");
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
d3.csv("data.csv", type, function(error, data) {
xScale.domain(data.map(xValue)); // data.map(xValue) returns an array of years
yScale.domain([0, d3.max(data, yValue)]);
// Note: domain for ordinal needs to be the whole range, not just min/max
console.log ("data.map(xValue) = ", data.map(xValue));
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("x", margin.left + 20)
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Dogs Eaten");
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", xMap)
.attr("width", xScale.rangeBand)
.attr("y", yMap)
.attr("height", function(d) { return height - yMap(d); })
.attr("style", function(d) {if (d.NewRecord == 1) return "fill:green";})
.attr("debug", function (d) {console.log(d);
console.log("x data = ", xValue(d));
console.log("x pixel = ", xMap(d));
console.log("y data = ", yValue(d));
console.log("y pixel = ", yMap(d));
console.log("width = ", xScale.rangeBand(d));
});
});
function type(d) {
d.DogsEaten = +d.DogsEaten; // change string into number format
return d;
}
</script>
https://d3js.org/d3.v3.min.js