Skip to content

Instantly share code, notes, and snippets.

@zawarudo
Created January 27, 2014 04:01
Show Gist options
  • Save zawarudo/8643066 to your computer and use it in GitHub Desktop.
Save zawarudo/8643066 to your computer and use it in GitHub Desktop.
Line plot with node click animation
<html>
<head>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<style>
text {
fill: #ccc;
}
path {
fill: none;
stroke-width: 2px;
stroke: rgb(0,0,200);
}
</style>
</head>
<body>
<div id="chart">
</div>
<script type="text/javascript">
var circRadius, hoverRadius, data, h, h2, w, w2, max, margin, vis, x, y, inDuration, outDuration;
circRadius = 5;
hoverRadius = circRadius * 1.5;
data = [1,1.5,1,1,1.5,1.5,2];
margin = {top: 10, bottom: 10, left: 10, right: 10};
w = 800;
h = 300;
w2 = w - margin.left - margin.right;
h2 = h - margin.top - margin.bottom;
inDuration = 1400;
outDuration = 800;
max = d3.max(data);
x = d3.scale.linear().domain([0, data.length - 1]).range([0, w2]);
y = d3.scale.linear().domain([0, max]).range([h2, 0]);
vis = d3.select('#chart')
.attr('width', w)
.attr('height', h)
.append('svg:svg')
.attr('width',w)
.attr('height', h)
.attr('class', 'viz')
.append('svg:g')
.attr('width',w2)
.attr('height', h2)
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
vis.selectAll('path.line')
.data([data])
.enter()
.append("svg:path")
.attr("d", d3.svg.line()
.x(function(d, i) { return x(i); })
.y(y));
vis.selectAll('.point').data(data).enter().append("svg:circle")
.attr("r", circRadius)
.attr("cx", function(d, i) {
return x(i);
}).attr("cy", function(d) {
return y(d);
})
.on('click', function(d, i) {
var clicked = d3.select(this);
if ( clicked.attr('r') > hoverRadius ) {
return clicked.transition().attr('r', circRadius).duration(outDuration);
} else {
return clicked.transition().attr('r', w).duration(inDuration);
}
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment