Skip to content

Instantly share code, notes, and snippets.

@pyrobot
Created November 21, 2012 03:39
Show Gist options
  • Save pyrobot/4122874 to your computer and use it in GitHub Desktop.
Save pyrobot/4122874 to your computer and use it in GitHub Desktop.
start / end graph
<!doctype html>
<html>
<head>
<script src="http://d3js.org/d3.v2.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.2/underscore-min.js"></script>
<style>
.chart rect {
stroke: #FFF;
fill: steelblue;
}
.chart text {
font-size: 11px;
fill: black;
}
text.rule {
fill: black;
}
</style>
</head>
<body>
<script type="text/javascript">
(function () {
var chart, x, y, graphHeight, ends, data;
// initial data
data = [
{
start: 12
, end: 18
}
,{
start: 6
, end: 10
}
,{
start: 8
, end: 12
}
,{
start: 11
, end: 14
}
,{
start: 13
, end: 19
}
,{
start: 15
, end: 23
}
,{
start: 17
, end: 29
}
,{
start: 19
, end: 33
}
,{
start: 14
, end: 25
}
,{
start: 16
, end: 27
}
];
graphHeight = data.length * 20;
// create a seperate dataset of just the data[n].end parts
ends = _.map(data, function (d) { return d.end; });
// create the x/y positioning helpers
x = d3.scale.linear()
.domain([0, d3.max(ends)])
.range([0, 420]);
y = d3.scale.ordinal()
.domain(ends)
.rangeBands([0, graphHeight]);
// initialize the chart
chart = d3.select("body")
.append("svg")
.attr("class", "chart")
.attr("width", 500)
.attr("height", 20 + graphHeight)
.append("g")
.attr("transform", "translate(10,15)")
// create the bars
chart.selectAll("rect")
.data(data)
.enter()
.append("rect")
.attr("x", function (d) { return x(d.start); })
.attr("y", function (d, i) {
return i * 20;
})
.attr("width", function (d) { return x(d.end - d.start); } )
.attr("height", y.rangeBand());
// add the starting text labels
chart.selectAll("text")
.data(data)
.enter()
.append("text")
.attr("x", function (d) { return x(d.start); })
.attr("y", function (d) { return y(d.end) + y.rangeBand() / 2; })
.attr("dx", -3)
.attr("dy", ".35em")
.attr("text-anchor", "end")
.text(function (d) { return String(d.start) } )
// add the ending text labels
chart.selectAll(".ends")
.data(ends)
.enter()
.append("text")
.attr("x", x)
.attr("y", function (d) { return y(d) + y.rangeBand() / 2; })
.attr("dx", +3)
.attr("dy", ".35em")
.attr("text-anchor", "start")
.text(String);
// create the x ticks
chart.selectAll("line")
.data(x.ticks(10))
.enter()
.append("line")
.attr("x1", x)
.attr("x2", x)
.attr("y1", 0)
.attr("y2", graphHeight)
.style("stroke", "#ccc");
// add range labels
chart.selectAll(".rule")
.data(x.ticks(10))
.enter()
.append("text")
.attr("class", "rule")
.attr("x", x)
.attr("y", 0)
.attr("dy", -3)
.attr("text-anchor", "middle")
.text(String);
// add origin Y axis line
chart.append("line")
.attr("y1", 0)
.attr("y2", graphHeight)
.style("stroke", "#000");
})();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment