Skip to content

Instantly share code, notes, and snippets.

@dkandalov
Last active December 14, 2015 09:39
Show Gist options
  • Select an option

  • Save dkandalov/5066611 to your computer and use it in GitHub Desktop.

Select an option

Save dkandalov/5066611 to your computer and use it in GitHub Desktop.
simple d3 script for displaying timebased events from csv
var csv = ""; // paste csv into this string
var margin = {top: 20, right: 20, bottom: 30, left: 50},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var parseFormat = d3.time.format("%H:%M:%S");
var displayFormat = d3.time.format("%H:%M");
var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);
var xAxis = d3.svg.axis().scale(x).orient("bottom").tickFormat(displayFormat).ticks(25);
var yAxis = d3.svg.axis().scale(y).orient("left");
var line = d3.svg.line()
.x(function(d) { return x(d.eventTime); })
.y(function(d) { return y(d.value1); });
d3.select("style").text("\
body {\
font: 10px sans-serif;\
}\
.axis path,\
.axis line {\
fill: none;\
stroke: #000;\
shape-rendering: crispEdges;\
}\
.line {\
fill: none;\
stroke: steelblue;\
stroke-width: 1.5px;\
}\
");
d3.selectAll("svg").remove();
var svg = d3.select("body").attr({ font: "10px sans-serif" })
.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 + ")");
var data = d3.csv.parseRows(csv);
data.shift();
data = data.map(function(line) {
return { eventTime: parseFormat.parse(line[0]), value1: parseInt(line[1]) };
});
x.domain(d3.extent(data, function(d){ return d.eventTime; }));
y.domain(d3.extent(data, function(d){ return d.value1; }));
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("path")
.datum(data)
.attr("class", "line")
.attr({ d: line });
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("milliseconds");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment