Skip to content

Instantly share code, notes, and snippets.

@rmarimon
Created July 8, 2011 03:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rmarimon/1071070 to your computer and use it in GitHub Desktop.
Save rmarimon/1071070 to your computer and use it in GitHub Desktop.
Date ticks
Date ticks example
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>date ticks</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.js"></script>
<style type="text/css">
.xaxis {
stroke: black;
stroke-width: 2px;
}
.tick {
stroke: red;
stroke-width: 2px;
}
</style>
</head>
<body>
<button id="button">Redraw</button>
<div id="chart" style="width:100%;height:300px;"></div>
<script type="text/javascript">
draw();
d3.select('#button').on('click', draw);
function draw() {
// some fake date data sorted
var d = Math.floor(Math.random()*31),
from = new Date(2010, 0, 1),
to = new Date(2010, 0, d + 1);
// chart
var w = $('#chart').width(),
h = $('#chart').height(),
x = d3.scale.linear().domain([from, to]).range([0, w]);
var vis = d3.select('#chart').select('svg').select('g');
if (vis.empty()) {
vis = d3.select('#chart')
.append('svg:svg')
.attr('width', w)
.attr('height', h)
.append('svg:g');
}
var t = vis.selectAll('line.tick')
.data(days(x.domain()));
t.transition().duration(3000)
.attr('x1', x)
.attr('x2', x);
t.enter().append('svg:line')
.transition().delay(3000)
.attr('class', 'tick')
.attr('x1', x)
.attr('x2', x)
.attr('y1', h - 20)
.attr('y2', h - 10);
t.exit()
.attr('y1', h - 30)
.attr('y2', h - 20)
.transition().duration(3000)
.style('opacity', 0)
.remove();
vis.selectAll('line.xaxis')
.data([1])
.enter().append('svg:line')
.attr('class', 'xaxis')
.attr('x1', 0)
.attr('x2', w)
.attr('y1', h - 15)
.attr('y2', h - 15);
}
function days(domain) {
var d0 = domain[0],
d1 = domain[1],
dz = [];
d0 += 864e5 - (d0 % 864e5 || 864e5);
while (d0 <= d1) {
dz.push(new Date(d0));
d0 += 864e5;
}
return dz;
}
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment