|
<!DOCTYPE html> |
|
<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="http://d3js.org/d3.v3.min.js"></script> |
|
<script> |
|
|
|
var margin = {top: 20, right: 20, bottom: 50, 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> |