Skip to content

Instantly share code, notes, and snippets.

@xeophin
Forked from stepheneb/index.html
Last active August 22, 2018 19:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xeophin/a6a5c54bdea054e0923f079e5baab993 to your computer and use it in GitHub Desktop.
Save xeophin/a6a5c54bdea054e0923f079e5baab993 to your computer and use it in GitHub Desktop.
D3 Example: Processing a nested json data structure with subsections
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>D3: Subselection Example</title>
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.js"></script>
<style type="text/css">
body {
font: 13px sans-serif;
}
ul {
list-style: none;
font-weight: bold;
}
li {
margin: 0.2em 0.0em;
padding: 0.5em 1.0em;
font-weight: normal;
}
</style>
</head>
<body>
<script type="text/javascript">
var questions = [
{ "prompt": "Why is the sky blue?",
"responses": [
"Because the color blue was on sale at Wallmart",
"Because blue is the prettiest color",
"Because the air molecules difract blue light more than any other color"
]
},
{ "prompt": "Why are leaves usually green?",
"responses": [
"So green caterpillars can hide better.",
"Because leaves can more easily make energy with green light",
"Because leaves absorb red and blue light so it's green that is reflected"
]
}
];
var rows = d3.select("body").select('table').selectAll("tr")
.data(questions)
.enter().append("tr")
rows
.append('th')
.text(function(d) { return d.prompt })
var contentCell = rows
.append('td')
contentCell.selectAll('div')
.data(function(d) { return d.responses; })
.enter().append("div")
.text(function(d) { return d })
.style("background-color", function(d, i) { return i % 2 ? "#eee" : "#ddd"; });
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment