Skip to content

Instantly share code, notes, and snippets.

@nelliemckesson
Last active December 15, 2015 19:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save nelliemckesson/5315143 to your computer and use it in GitHub Desktop.
Save nelliemckesson/5315143 to your computer and use it in GitHub Desktop.
Basic D3.js "percent complete" bar
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="http://d3js.org/d3.v2.js"></script>
<link href="styles.css" rel="stylesheet" type="text/css" />
<title>"Percent complete" bar</title>
</head>
<body>
<div id="container"></div> <!--d3 chart gets inserted in this div-->
<script>
// based on this tutorial: http://mbostock.github.com/d3/tutorial/bar-1.html
// with adjustments and stuff
// see it here: http://jsbin.com/avemek/2/
var data = [560, 350]; // here are the data values; v1 = total, v2 = current value
var chart = d3.select("#container").append("svg") // creating the svg object inside the container div
.attr("class", "chart")
.attr("width", 200) // bar has a fixed width
.attr("height", 20 * data.length);
var x = d3.scale.linear() // takes the fixed width and creates the percentage from the data values
.domain([0, d3.max(data)])
.range([0, 200]);
chart.selectAll("rect") // this is what actually creates the bars
.data(data)
.enter().append("rect")
.attr("width", x)
.attr("height", 20)
.attr("rx", 5) // rounded corners
.attr("ry", 5);
chart.selectAll("text") // adding the text labels to the bar
.data(data)
.enter().append("text")
.attr("x", x)
.attr("y", 10) // y position of the text inside bar
.attr("dx", -3) // padding-right
.attr("dy", ".35em") // vertical-align: middle
.attr("text-anchor", "end") // text-align: right
.text(String);
</script>
</body>
</html>
.chart rect:first-of-type {
color: #fff;
stroke: #3994b6;
fill: white;
}
text:first-of-type {
fill: #3994b6;
font-family: sans-serif;
font-size: 12px;
}
.chart rect:nth-of-type(2) {
color: #fff;
stroke: transparent;
fill: #3994b6;
}
text:nth-of-type(2) {
fill: #a8d4e4;
font-family: sans-serif;
font-size: 12px;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment