JSFiddle - React, Tailwind, and code Playground
by samselikoff
HTML
<script src="http://d3js.org/d3.v3.min.js"></script>
<div class="chart"></div>
CSS
.chart path {
fill: none;
}
.chart .axis path, .chart .axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.chart {
font-family: "Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif;
font-size: 11px;
color: #999999;
height: 210px;
clear: both;
}
JavaScript
// dataset1
var dataset1 = new Array();
for (var day=10; day < 30; day++) {
for (hour=10; hour < 24; hour++) {
dataset1.push({
'date': '2013-02-'+day+' '+hour+':00:00',
'prod': Math.floor(Math.random()*200),
'robo': Math.floor(Math.random()*100),
'other':Math.floor(Math.random()*50)
});
}
}
// dataset2, a subset of dataset1
var dataset2 = new Array();
$.each(dataset1, function(i, obj) {
$.each(obj, function(k, v) {
if ( (k == 'date') && (v <= '2013-02-17 00:00:00') ) {
dataset2.push(obj);
}
});
});
// Draw and update the chart.
$(document).ready(function () {
var chart = TimeSeriesChart();
d3.select(".chart")
.datum(dataset1)
.call(chart);
setTimeout(function() {
d3.select(".chart")
.datum(dataset2)
.call(chart);
}, 2000)
});
// The chart object.
function TimeSeriesChart() {
var margin = {top: 40, right: 20, bottom: 40, left: 30};
width = 620 - margin.left - margin.right,
height = 210 - margin.top - margin.bottom,
xScale = d3.time.scale(),
yScale = d3.scale.linear(),
xAxis = d3.svg.axis().scale(xScale).orient("bottom").ticks(7),
yAxis = d3.svg.axis().scale(yScale).orient("left"),
line = d3.svg.line().interpolate("basis").x(X).y(Y),
parseDate = d3.time.format("%Y-%m-%d %X").parse,
color = d3.scale.category10();
function chart(selection) {
selection.each(function(data)
{
// Set the domain of the color scale to all categories but date (prod, robo, other in our case)
color.domain(d3.keys(data[0]).filter(function(key) { return key !== "date"; }));
data.forEach(function(d) {
if (!d.date.getMonth) {
d.date = parseDate(d.date);
}
});
// Construct a series object of our data.
// We start with ['prod', 'robo', 'other'] and the function...