Skip to content

Instantly share code, notes, and snippets.

@jorgeehernandez
Created September 7, 2016 12:38
Show Gist options
  • Save jorgeehernandez/0fd0080aa77ea52304ce233d671ce485 to your computer and use it in GitHub Desktop.
Save jorgeehernandez/0fd0080aa77ea52304ce233d671ce485 to your computer and use it in GitHub Desktop.
fresh block
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
</style>
</head>
<body>
<script>
// Feel free to change or delete any of the code you see in this editor!
var myData=[12, 15, 20, 50];
var margin = {top: 20, right: 20, bottom: 30, left: 40},
width = 200 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var wScale = d3.scaleLinear()
.range([0, width]);
var colScale = d3.scaleOrdinal(d3.schemeCategory20);
var BAR_HEIGHT = 20;
var svg = d3.select("#chart").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var xAxis = svg.append("g")
.attr("class", "axis x--axis");
wScale.domain([0, d3.max(myData)]);
var bars = svg.selectAll(".bars")
.data(myData);
//Enter
var barsEnter = bars.enter()
.append("rect")
.attr("class", "bars")
.attr("width", 0);
//Exit
bars.exit()
.transition()
.duration(1000)
.attr("width", 0)
.remove();
//Update
bars.merge(barsEnter)
.attr("x", 0)
.attr("y", function(d, i ) { return i * (BAR_HEIGHT+1);})
.attr("height", BAR_HEIGHT)
.style("fill", function(d,i) { return colScale(i); })
.transition().duration(1000)
.attr("width", function(d) { return wScale(d); });
xAxis
.transition()
.duration(1000)
.call(d3.axisTop()
.scale(wScale)
.ticks(3));
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment