Skip to content

Instantly share code, notes, and snippets.

@eesur
Last active August 29, 2015 13:58
Show Gist options
  • Save eesur/9935545 to your computer and use it in GitHub Desktop.
Save eesur/9935545 to your computer and use it in GitHub Desktop.
d3 | svg shapes with labels

Pulling in data to display svg shapes with labels

Data is of varying planetary years in earth days.

The planets revolve around the sun in different amounts of time, so a "year" on each planet is a different amount of time. The farther a planet is from the sun, the longer its year. source

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>D3 Json</title>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<style>
body {font-family: monospace; line-height: 160%; font-size: 16px; max-width: 90%; margin: 10px auto;}
</style>
</head>
<body>
<h3>Earth days to orbit our sun</h3>
<script>
var dataset = // embedded json , data from http://www.enchantedlearning.com/subjects/astronomy/age.shtml
[
{ "planet": "Mercury", "age" : 87.96, "colour" : "grey" },
{ "planet": "Venus", "age" : 224.68, "colour" : "purple" },
{ "planet": "Earth", "age" : 365.26, "colour" : "blue" },
{ "planet": "Mars", "age" : 686.98, "colour" : "red" },
{ "planet": "Jupiter", "age" : 4332.7141, "colour" : "green" },
{ "planet": "Saturn", "age" : 10759.0986, "colour" : "yellow" },
{ "planet": "Uranus", "age" : 30707.4082, "colour" : "pink" },
{ "planet": "Neptune", "age" : 60198.5006, "colour" : "black" },
];
// width and height
var w = 900;
var h = 500;
var x = d3.scale.linear()
.domain([0, d3.max(dataset, function(d) { return d.age; })])
.range([0, h]);
var theCanvas = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
var bars = theCanvas.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("width", function(d) {
return x(d.age);
})
.attr("fill", function(d) {
if (d["age"] <= 366) {
return "red";
} else {
return "black";
}
})
.attr("height", 16)
.attr("y", function (d, i) {
return i * 25;
});
//Add the SVG Text Element to the svgContainer
var text = theCanvas.selectAll("text")
.data(dataset)
.enter()
.append("text");
//Add SVG Text Element Attributes
var textLabels = text
.attr("x", function(d) { return x(d.age) + 10; })
.attr("y", function (d, i) {
return i * 25 + 14;
})
.text( function (d) { return d["planet"] + " takes " + d["age"]; })
.attr("font-family", "monospace")
.attr("font-size", "14px")
.attr("fill", "black");
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment