Skip to content

Instantly share code, notes, and snippets.

@fabiomainardi
Last active November 10, 2018 09:23
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 fabiomainardi/00fd581dc5ba92d99eec to your computer and use it in GitHub Desktop.
Save fabiomainardi/00fd581dc5ba92d99eec to your computer and use it in GitHub Desktop.
Filtering data

This is a simple development of a an example from the book "Data Visualization with D3.js Cookbook". Its purpose is to illustrate how to use the .filter statement directly in the .data statement:

.data(data.filter(function(d){return d.category == category;}))

<!DOCTYPE html>
<html>
<style>
.h-bar {
min-height:15px;
min-width: 10px;
width:0px;
height:0px;
background-color: steelblue;
margin-bottom: 2px;
font-size: 11px;
color: #f0f8ff;
text-align: right;
padding-right: 2px;
}
.control-group {
padding-top: 10px;
margin: 10px;
}
.selected {
background-color: #f08080;
}
</style>
<head>
<meta charset="utf-8">
<title>Data Filter</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
</head>
<body>
<script type="text/javascript">
var data = [ // <-A
{expense: 10, category: "Retail"},
{expense: 15, category: "Gas"},
{expense: 30, category: "Retail"},
{expense: 50, category: "Dining"},
{expense: 80, category: "Gas"},
{expense: 65, category: "Retail"},
{expense: 55, category: "Gas"},
{expense: 30, category: "Dining"},
{expense: 20, category: "Retail"},
{expense: 10, category: "Dining"},
{expense: 8, category: "Gas"}
];
function render(data, category) {
d3.select("body").selectAll("div.h-bar") // <-B
.data(data.filter(function(d){return d.category == category;}))
.enter()
.append("div")
.attr("class", "h-bar")
.append("span");
d3.select("body").selectAll("div.h-bar") // <-D
.data(data.filter(function(d){return d.category == category;}))
.attr("class", "h-bar")
.style("width", function (d) {
return (d.expense * 5) + "px";}
)
.select("span")
.text(function (d) {
return d.category;
});
d3.select("body").selectAll("div.h-bar") // <-C
.data(data.filter(function(d){return d.category == category;}))
.exit().remove();
/* d3.select("body").selectAll("div.h-bar")
.filter(function (d, i) { // <-E
return d.category == category;
})
.classed("selected", true);
console.log(data);*/
}
// render(data);
function select(category) {
render(data, category);
}
</script>
<div class="control-group">
<button onclick="select('Retail')">
Retail
</button>
<button onclick="select('Gas')">
Gas
</button>
<button onclick="select('Dining')">
Dining
</button>
<button onclick="select()">
Clear
</button>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment