Based on examples made by Scott Murray - alignedleft
- css fill transition
- assigning transitions by class of elements
- filtering data by assigning classes using .classed
- using .each with .select(this) to dynamically assign classes
Based on examples made by Scott Murray - alignedleft
<!DOCTYPE html> | |
<head> | |
<meta charset="utf-8"> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script> | |
<title>D3: Smoothing out the highlights</title> | |
<script type="text/javascript" src="d3.js"></script> | |
<style type="text/css"> | |
body { | |
background-color: gray; | |
} | |
svg { | |
background-color: white; | |
} | |
svg rect { | |
fill: #3200ff; | |
/* New transition rule sets speed of fill changes, | |
such as when the "highlight" class is applied. */ | |
transition: fill 0.7s ease-in; | |
} | |
svg rect.highlight { | |
fill: #ff759a; | |
} | |
.axis path, | |
.axis line { | |
fill: none; | |
stroke: black; | |
shape-rendering: crispEdges; | |
} | |
.axis text { | |
font-family: sans-serif; | |
font-size: 11px; | |
} | |
</style> | |
</head> | |
<body> | |
<script type="text/javascript"> | |
//Width, height, padding | |
var w = 600; | |
var h = 250; | |
var padding = 25; | |
//Array of dummy data values | |
var dataset = [ 23, 19, 22, 19, 21, 25, 22, 18, 15, 13, | |
3, 1, 5, 2, 18, 17, 21, 18, 23, 25 ]; | |
//Configure x and y scale functions | |
var xScale = d3.scale.ordinal() | |
.domain(d3.range(dataset.length)) | |
.rangeRoundBands([ padding, w - padding ], 0.05); | |
var yScale = d3.scale.linear() | |
.domain([ 0, d3.max(dataset) ]) | |
.rangeRound([ h - padding, padding ]); | |
//Configure y axis generator | |
var yAxis = d3.svg.axis() | |
.scale(yScale) | |
.orient("left") | |
.ticks(5); | |
//Create SVG element | |
var svg = d3.select("body") | |
.append("svg") | |
.attr("width", w) | |
.attr("height", h); | |
//Create bars | |
var rects = svg.selectAll("rect") | |
.data(dataset) | |
.enter() | |
.append("rect") | |
.attr("x", function(d, i) { | |
return xScale(i); | |
}) | |
.attr("y", function(d) { | |
return h - padding; | |
}) | |
.attr("width", xScale.rangeBand()) | |
.attr("height", 0); | |
//Transition rects into place | |
rects.transition() | |
.delay(function(d, i) { | |
return i * 100; | |
}) | |
.duration(1500) | |
.attr("y", function(d) { | |
return yScale(d); | |
}) | |
.attr("height", function(d) { | |
return h - padding - yScale(d); | |
}) | |
.each("end", function(d) { | |
d3.select(this) | |
.classed("highlight", function(d) { | |
if (d > 20) { | |
return true; | |
} | |
return false; | |
}); | |
}); | |
//Create y axis | |
svg.append("g") | |
.attr("class", "axis") | |
.attr("transform", "translate(" + padding + ",0)") | |
.attr("opacity", 0) | |
.call(yAxis) | |
.transition() | |
.delay(2000) | |
.duration(1500) | |
.attr("opacity", 1.0); | |
</script> | |
</body> | |
</html> |