d3js: d3.nest() and filter() using Select box and svg circles.
Last active
December 25, 2015 17:09
-
-
Save jfreels/7010699 to your computer and use it in GitHub Desktop.
d3js: d3.nest() and filter() using Select box and svg circles.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<meta charset='utf-8'> | |
<html> | |
<head> | |
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script> | |
<link rel='stylesheet' href='style.css'> | |
</head> | |
<body> | |
<script type='text/javascript' src='script.js'></script> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var data = [ | |
{ | |
"color" : "red", | |
"cx" : 25, | |
"cy" : 25, | |
"r" : 10 | |
}, | |
{ | |
"color" : "green", | |
"cx" : 55, | |
"cy" : 55, | |
"r" : 20 | |
}, | |
{ | |
"color" : "blue", | |
"cx" : 75, | |
"cy" : 75, | |
"r" : 30 | |
} | |
] | |
var dataNested = d3.nest() | |
.key(function (d) { return d.color; }) | |
.entries(data) | |
d3.select('body').append('div') | |
.append('select') | |
.on('change',change) | |
.selectAll('option') | |
.data(dataNested) | |
.enter() | |
.append('option') | |
.attr('value',function (d) { return d.key }) | |
.text(function (d) { return d.key }) | |
var dataFiltered = dataNested.filter(function (d) { return d.key === 'red' }) | |
var svg = d3.select('body').append('svg') | |
.attr('height',150) | |
.attr('width',150) | |
var circles = svg.selectAll('circle') | |
.data(dataFiltered[0].values) | |
circles.enter() | |
.append('circle') | |
.attr('cx', function (d) { return d.cx }) | |
.attr('cy', function (d) { return d.cy }) | |
.attr('r', function (d) { return d.r }) | |
.attr('fill', function (d) { return d.color }) | |
function change() { | |
var value = this.value | |
dataFiltered = dataNested.filter(function (d) { return d.key === value }) | |
circles.data(dataFiltered[0].values) | |
.transition().duration(1000) | |
.attr('cx', function (d) { return d.cx }) | |
.attr('cy', function (d) { return d.cy }) | |
.attr('r', function (d) { return d.r }) | |
.attr('fill', function (d) { return d.color }) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* CSS Here |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment