Built with blockbuilder.org
Last active
April 17, 2018 14:52
-
-
Save nbremer/da7c187aee6c26981e33d9d8e3c1d3a9 to your computer and use it in GitHub Desktop.
Simple animated bar chart
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
license: mit |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<head> | |
<meta charset="utf-8"> | |
<script src="https://d3js.org/d3.v5.min.js"></script> | |
<style> | |
body { text-align: center; } | |
svg { margin-top: 50px; } | |
</style> | |
</head> | |
<body> | |
<script> | |
var dataset = [ 5, 10, 4, 7, 8, 12, 15, 3, 16, 18, 7, 19, 14, 7 ]; | |
var totalHeight = 100; | |
var yScale = d3.scaleLinear() | |
.domain([0, d3.max(dataset)]) | |
.range([0, totalHeight]); | |
var colorScale = d3.scaleLinear() | |
.domain([0, d3.max(dataset)/2, d3.max(dataset)]) | |
.range(["#e89f84", "#BF4E24", "#6c2c14"]); | |
var svg = d3.select("body").append("svg") | |
.attr("width", 300) | |
.attr("height", 400); | |
var bars = svg.selectAll(".bars") | |
.data(dataset) | |
.enter().append("rect") | |
.attr("class", "bars") | |
.attr("width", 15) | |
.attr("height", 0) | |
.attr("x", function(d,i) { return i*20; }) | |
.attr("y", totalHeight) | |
.style("fill", function(d) { return colorScale(d); }); | |
bars.on("mouseover", function(d) { | |
d3.select(this) | |
.style("fill", "#D3D3D3"); | |
}) | |
.on("mouseout", function(d) { | |
d3.select(this) | |
.transition().duration(600) | |
.style("fill", function(d) { return colorScale(d); }); | |
}); | |
bars.transition().duration(500) | |
.delay(function(d,i) { return i*200; }) | |
.attr("y", function(d) { return totalHeight - yScale(d); }) | |
.attr("height", function(d) { return yScale(d); }); | |
</script> | |
</body> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment