Skip to content

Instantly share code, notes, and snippets.

@cramhead
Last active June 14, 2017 20:57
Show Gist options
  • Save cramhead/f6f4f96bde79bf548e0f776aa3396656 to your computer and use it in GitHub Desktop.
Save cramhead/f6f4f96bde79bf548e0f776aa3396656 to your computer and use it in GitHub Desktop.
Sample chart from Mike's tutorial https://bost.ocks.org/mike/bar/2/
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; }
.chart rect {
fill: steelblue;
}
.chart text {
fill: white;
font: 10px sans-serif;
text-anchor: end;
}
</style>
</head>
<body>
<div class="chart" />
<script>
var data = [4, 8, 15, 16, 23, 42];
var width = 960, height = 500;
var barHeight = 20;
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
var x = d3.scaleBand().domain(data).range([0, width])
var y = d3.scaleLinear().domain(data)
.range([height, 0]);
var chart = svg.append('g').attr('class', 'chart')
.attr("width", width)
.attr("height", barHeight * data.length);
var bar = chart.selectAll("g")
.data(data)
.enter().append("g")
.attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; });
bar.append("rect")
.attr("width", x)
.attr("height", barHeight - 1);
bar.append("text")
.attr("x", function(d) { return x(d) - 3; })
.attr("y", barHeight / 2)
.attr("dy", ".35em")
.text(function(d) { return d; });
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment