JSFiddle - React, Tailwind, and code Playground
by chrismetcalf
HTML
<script src="http://d3js.org/d3.v3.min.js"></script>
CSS
body {
font: 10px sans-serif;
}
.axis path, .axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.bar {
fill: steelblue;
}
.x.axis path {
display: none;
}
JavaScript
// Set our margins
var margin = {
top: 20,
right: 20,
bottom: 30,
left: 60
},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
// Our X scale
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
// Our Y scale
var y = d3.scale.linear()
.rangeRound([height, 0]);
// Our color bands
var color = d3.scale.ordinal()
.range(["#308fef", "#5fa9f3", "#1176db"]);
// Use our X scale to set a bottom axis
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
// Smae for our left axis
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.tickFormat(d3.format(".2s"));
// Add our chart to the document body
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 + ")");
// Fetch data via SODA from the Chicago data site
d3.csv("https://data.cityofchicago.org/resource/w8km-9pzd.csv?$select=year,bus,paratransit,rail", function (error, data) {
// Make sure our numbers are really numbers
data.forEach(function (d) {
d.year = +d.year;
d.bus = +d.bus;
d.paratransit = +d.paratransit;
d.rail = +d.rail;
});
console.log(data);
// Use our values to set our color bands
color.domain(d3.keys(data[0]).filter(function (key) {
return key !== "year";
}));
data.forEach(function (d) {
var y0 = 0;
d.types = color.domain().map(function (name) {
return {
name: name,
y0: y0,
y1: y0 += +d[name]
};
});
d.total = d.types[d.types.length - 1].y1;
});
// Sort by year
data.sort(function (a, b) {
return a.year - b.year;
});
// Our X domain is our set of years
x.domain(data.map(function (d) {
return d.year;
...