Skip to content

Instantly share code, notes, and snippets.

@eychang9
Last active January 9, 2018 03:48
Show Gist options
  • Save eychang9/4b97ed3448690a27360b66fbc5ea9f54 to your computer and use it in GitHub Desktop.
Save eychang9/4b97ed3448690a27360b66fbc5ea9f54 to your computer and use it in GitHub Desktop.
Ch9_Bar_Base
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; }
.txtLabel {
font-family: Century Gothic;
font-size: 12px;
}
</style>
</head>
<body>
<script>
// Dataset and other constants
var dataset = [ 5, 10, 13, 19, 21, 25, 22, 18, 15, 13,
11, 12, 15, 20, 18, 17, 16, 18, 23, 25 ];
var svgW = 900;
var svgH = 500;
var pad = 100;
// Develop axial scales
var xScale = d3.scaleBand()
.domain(d3.range(dataset.length))
.rangeRound([pad, svgW-pad])
.paddingInner(0.05);
var yScale = d3.scaleLinear()
.domain([0, d3.max(dataset, function (d) { return (d);})])
.rangeRound([svgH-pad, pad])
// Establish SVG
var svg = d3.select("body")
.append("svg")
.attr("width", svgW)
.attr("height", svgH)
// Draw rectangles
svg.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("x", function (d,i) { return xScale(i); })
.attr("y", function (d) { return yScale(d); })
.attr("width", xScale.bandwidth())
.attr("height", function (d) { return (svgH-pad-yScale(d)); })
.attr("fill", function (d) { return "rgb(0,0," + d*10 + ")" });
// Draw text
svg.selectAll("text")
.data(dataset)
.enter()
.append("text")
.attr("x", function (d,i) { return (xScale(i) + 0.5 * xScale.bandwidth());})
.attr("y", function (d) { return (yScale(d) + 15); })
.text(function (d) { return (d);})
.attr("fill", "rgb(255,255,255)")
.attr("text-anchor", "middle")
.attr("class", "txtLabel");
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment