An example set of coordinated views that use Crossfilter and Chiasm.
Draws from:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Chiasm Crossfilter Integration</title>
<!-- A functional reactive model library. See github.com/curran/model -->
<script src="//curran.github.io/model/cdn/model-v0.2.4.js"></script>
<!-- The common base for Chiasm components (depends on Model.js). -->
<script src="//chiasm-project.github.io/chiasm-component/chiasm-component-v0.2.1.js"></script>
<!-- This script defines the BarChart component. -->
<script src="barChart.js"> </script>
<!-- Load Crossfilter and the Crossfilter Chiasm component. -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/crossfilter/1.3.12/crossfilter.min.js"></script>
<script src="chiasm-crossfilter.js"></script>
<!-- This plugin loads CSV data sets. -->
<script src="chiasm-csv-loader.js"></script>
<!-- This does custom data preprocessing for the flight data. -->
<script src="flights-preprocessor.js"></script>
<!-- Chiasm.js depends on Model.js, Lodash.js, D3.js. -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script>
<!-- Chiasm.js and plugins. See github.com/chiasm-project -->
<script src="//chiasm-project.github.io/chiasm/chiasm-v0.2.0.js"></script>
<script src="//chiasm-project.github.io/chiasm-layout/chiasm-layout-v0.2.2.js"></script>
<script src="//chiasm-project.github.io/chiasm-links/chiasm-links-v0.2.1.js"></script>
<!-- Make the Chiasm container fill the page and have a 20px black border. -->
<style>
body {
background-color: black;
}
#chiasm-container {
background-color: white;
position: fixed;
left: 20px;
right: 20px;
top: 20px;
bottom: 20px;
}
</style>
</head>
<body>
<!-- Chiasm component DOM elements will be injected into this div. -->
<div id="chiasm-container"></div>
<!-- This is the main program that sets up the Chiasm application. -->
<script>
// Create a new Chiasm instance.
var chiasm = new Chiasm();
// Register plugins that the configuration can access.
chiasm.plugins.layout = ChiasmLayout;
chiasm.plugins.links = ChiasmLinks;
chiasm.plugins.barChart = BarChart;
chiasm.plugins.csvLoader = ChiasmCSVLoader;
chiasm.plugins.flightsPreprocessor = FlightsPreprocessor;
chiasm.plugins.crossfilter = ChiasmCrossfilter;
// Set the Chaism configuration.
chiasm.setConfig({
"layout": {
"plugin": "layout",
"state": {
"containerSelector": "#chiasm-container",
"layout": {
"orientation": "vertical",
"children": [
"hour-chart",
"delay-chart"
]
}
}
},
"hour-chart": {
"plugin": "barChart",
"state": {
"barSizeColumn": "value"
//,"barIdentityColumn": "key"
}
},
"delay-chart": {
"plugin": "barChart",
"state": {
"barSizeColumn": "value"
}
},
"flights-dataset": {
"plugin": "csvLoader",
"state": {
"path": "flights-3m"
}
},
"flights-preprocessor": {
"plugin": "flightsPreprocessor"
},
"flights-crossfilter": {
"plugin": "crossfilter",
"state": {
"groups": {
"dates": {
"dimension": "date",
"aggregation": "day"
},
"hours": {
"dimension": "hour",
"aggregation": "floor 1"
},
"delays": {
"dimension": "delay",
"aggregation": "floor 10"
},
"distances": {
"dimension": "distance",
"aggregation": "floor 50"
}
}
}
},
"links": {
"plugin": "links",
"state": {
"bindings": [
"flights-dataset.data -> flights-preprocessor.dataIn",
"flights-preprocessor.dataOut -> flights-crossfilter.data",
"flights-crossfilter.hours -> hour-chart.data",
"flights-crossfilter.delays -> delay-chart.data"
]
}
}
});
</script>
</body>
</html>
The MIT License (MIT)
Copyright (c) 2015 Curran Kelleher
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
// This is an example Chaism plugin that uses D3 to make a bar chart.
// Draws from this Bar Chart example http://bl.ocks.org/mbostock/3885304
function BarChart() {
var my = ChiasmComponent({
margin: {
left: 30,
top: 30,
right: 30,
bottom: 30
},
barSizeColumn: Model.None,
// These properties adjust spacing between bars.
// The names correspond to the arguments passed to
// d3.scale.ordinal.rangeRoundBands(interval[, padding[, outerPadding]])
// https://github.com/mbostock/d3/wiki/Ordinal-Scales#ordinal_rangeRoundBands
barPadding: 0.1,
barOuterPadding: 0.1,
fill: "black",
stroke: "none",
strokeWidth: "1px",
orientation: "vertical"
});
var barSizeScale = d3.scale.linear();
var barIdentityScale = d3.scale.ordinal();
my.el = document.createElement("div");
var svg = d3.select(my.el).append("svg");
var g = svg.append("g");
// Respond to changes in size and margin.
// Inspired by D3 margin convention from http://bl.ocks.org/mbostock/3019563
my.when(["box", "margin"], function(box, margin){
my.innerBox = {
width: box.width - margin.left - margin.right,
height: box.height - margin.top - margin.bottom
};
svg
.attr("width", box.width)
.attr("height", box.height);
g.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
});
my.when(["data", "barSizeColumn", "innerBox", "barPadding", "barOuterPadding", "fill", "stroke", "strokeWidth", "orientation"],
function (data, barSizeColumn, innerBox, barPadding, barOuterPadding, fill, stroke, strokeWidth, orientation){
var x, y, width, height;
barSizeScale
.domain([0, d3.max(data, function (d){ return d[barSizeColumn]; })]);
barIdentityScale
.domain(d3.range(data.length));
if(orientation === "vertical"){
barSizeScale.range([innerBox.height, 0]);
barIdentityScale.rangeRoundBands([0, innerBox.width], barPadding, barOuterPadding);
x = function(d, i) { return barIdentityScale(i); };
y = function(d) { return barSizeScale(d[barSizeColumn]); };
width = barIdentityScale.rangeBand();
height = function(d) { return innerBox.height - y(d); };
} else if(orientation === "horizontal"){
barSizeScale.range([0, innerBox.width]);
barIdentityScale.rangeRoundBands([0, innerBox.height], barPadding, barOuterPadding);
x = 0;
y = function(d, i) { return barIdentityScale(i); };
width = function(d) { return barSizeScale(d[barSizeColumn]); };
height = barIdentityScale.rangeBand();
}
var bars = g.selectAll("rect").data(data);
bars.enter().append("rect");
bars
.attr("x", x)
.attr("width", width)
.attr("y", y)
.attr("height", height)
.attr("fill", fill)
.attr("stroke", stroke)
.attr("stroke-width", strokeWidth);
bars.exit().remove();
});
return my;
}
// This function defines a Chiasm component that draws a colored rectangle using D3.js.
function BarChart() {
var my = new ChiasmComponent({
color: "white"
});
var svg = my.initSVG();
var rect = d3.select(svg).append("rect");
my.when("data", function (data){
console.log(data);
});
my.when("color", function (color){
rect.attr("fill", color);
});
my.when("box", function (box) {
rect
.attr("width", box.width)
.attr("height", box.height);
});
function barChart() {
if (!barChart.id) barChart.id = 0;
var margin = {top: 10, right: 10, bottom: 20, left: 10},
x,
y = d3.scale.linear().range([100, 0]),
id = barChart.id++,
axis = d3.svg.axis().orient("bottom"),
brush = d3.svg.brush(),
brushDirty,
dimension,
group,
round;
function chart(div) {
var width = x.range()[1],
height = y.range()[0];
y.domain([0, group.top(1)[0].value]);
div.each(function() {
var div = d3.select(this),
g = div.select("g");
// Create the skeletal chart.
if (g.empty()) {
div.select(".title").append("a")
.attr("href", "javascript:reset(" + id + ")")
.attr("class", "reset")
.text("reset")
.style("display", "none");
g = div.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
g.append("clipPath")
.attr("id", "clip-" + id)
.append("rect")
.attr("width", width)
.attr("height", height);
g.selectAll(".bar")
.data(["background", "foreground"])
.enter().append("path")
.attr("class", function(d) { return d + " bar"; })
.datum(group.all());
g.selectAll(".foreground.bar")
.attr("clip-path", "url(#clip-" + id + ")");
g.append("g")
.attr("class", "axis")
.attr("transform", "translate(0," + height + ")")
.call(axis);
// Initialize the brush component with pretty resize handles.
var gBrush = g.append("g").attr("class", "brush").call(brush);
gBrush.selectAll("rect").attr("height", height);
gBrush.selectAll(".resize").append("path").attr("d", resizePath);
}
// Only redraw the brush if set externally.
if (brushDirty) {
brushDirty = false;
g.selectAll(".brush").call(brush);
div.select(".title a").style("display", brush.empty() ? "none" : null);
if (brush.empty()) {
g.selectAll("#clip-" + id + " rect")
.attr("x", 0)
.attr("width", width);
} else {
var extent = brush.extent();
g.selectAll("#clip-" + id + " rect")
.attr("x", x(extent[0]))
.attr("width", x(extent[1]) - x(extent[0]));
}
}
g.selectAll(".bar").attr("d", barPath);
});
function barPath(groups) {
var path = [],
i = -1,
n = groups.length,
d;
while (++i < n) {
d = groups[i];
path.push("M", x(d.key), ",", height, "V", y(d.value), "h9V", height);
}
return path.join("");
}
function resizePath(d) {
var e = +(d == "e"),
x = e ? 1 : -1,
y = height / 3;
return "M" + (.5 * x) + "," + y
+ "A6,6 0 0 " + e + " " + (6.5 * x) + "," + (y + 6)
+ "V" + (2 * y - 6)
+ "A6,6 0 0 " + e + " " + (.5 * x) + "," + (2 * y)
+ "Z"
+ "M" + (2.5 * x) + "," + (y + 8)
+ "V" + (2 * y - 8)
+ "M" + (4.5 * x) + "," + (y + 8)
+ "V" + (2 * y - 8);
}
}
brush.on("brushstart.chart", function() {
var div = d3.select(this.parentNode.parentNode.parentNode);
div.select(".title a").style("display", null);
});
brush.on("brush.chart", function() {
var g = d3.select(this.parentNode),
extent = brush.extent();
if (round) g.select(".brush")
.call(brush.extent(extent = extent.map(round)))
.selectAll(".resize")
.style("display", null);
g.select("#clip-" + id + " rect")
.attr("x", x(extent[0]))
.attr("width", x(extent[1]) - x(extent[0]));
dimension.filterRange(extent);
});
brush.on("brushend.chart", function() {
if (brush.empty()) {
var div = d3.select(this.parentNode.parentNode.parentNode);
div.select(".title a").style("display", "none");
div.select("#clip-" + id + " rect").attr("x", null).attr("width", "100%");
dimension.filterAll();
}
});
chart.margin = function(_) {
if (!arguments.length) return margin;
margin = _;
return chart;
};
chart.x = function(_) {
if (!arguments.length) return x;
x = _;
axis.scale(x);
brush.x(x);
return chart;
};
chart.y = function(_) {
if (!arguments.length) return y;
y = _;
return chart;
};
chart.dimension = function(_) {
if (!arguments.length) return dimension;
dimension = _;
return chart;
};
chart.filter = function(_) {
if (_) {
brush.extent(_);
dimension.filterRange(_);
} else {
brush.clear();
dimension.filterAll();
}
brushDirty = true;
return chart;
};
chart.group = function(_) {
if (!arguments.length) return group;
group = _;
return chart;
};
chart.round = function(_) {
if (!arguments.length) return round;
round = _;
return chart;
};
return d3.rebind(chart, brush, "on");
}
return my;
}
// This function defines a Chiasm component that exposes a Crossfilter instance
// to visualizations via the Chaism configuration.
function ChiasmCrossfilter() {
var my = new ChiasmComponent({
groups: Model.None
});
my.when(["data", "groups"], function (data, groups){
if(groups !== Model.None) {
var cf = crossfilter(data);
Object.keys(groups).forEach(function (groupName){
var group = groups[groupName];
var cfDimension = cf.dimension(function (d){
return d[group.dimension];
});
var aggregate;
if(group.aggregation === "day"){
aggregate = d3.time.day;
} else if(group.aggregation.indexOf("floor") === 0){
var interval = parseInt(group.aggregation.substr(6));
aggregate = function(d) {
return Math.floor(d / interval) * interval;
};
}
var cfGroup = cfDimension.group(aggregate);
//console.log(cfGroup.all());
my[groupName] = cfGroup.all();
});
//var dimensions = {};
//listeners.forEach(my.cancel);
//listeners = [];
//dimensionProperties.forEach(function(property){
// var dimension = observation.dimension(function(d){ return d[property]; });
// dimensions[property] = dimension;
// listeners.push(my.when(property + "Filter", function(filter){
// dimension.filter(filter);
// updateAll();
// }));
//});
//function updateAll(){
// dimensionProperties.forEach(function(property){
// my[property + "Top"] = dimensions[property].top(Infinity);
// });
//}
//// Call once to initialize.
//updateAll();
}
});
return my;
}
function ChiasmCSVLoader (){
var my = ChiasmComponent({
path: Model.None
});
my.when("path", function (path){
if(path !== Model.None){
d3.json(path + ".json", function(error, schema) {
var numericColumns = schema.columns.filter(function (column){
return column.type === "number";
});
var type = function (d){
numericColumns.forEach(function (column){
d[column.name] = +d[column.name];
});
return d;
}
d3.csv(path + ".csv", type, function(error, data) {
my.data = data;
});
});
}
});
return my;
}
{
"columns": [
{ "name": "date", "type": "string" },
{ "name": "delay", "type": "number" },
{ "name": "distance", "type": "number" },
{ "name": "origin", "type": "string" },
{ "name": "destination", "type": "string" }
]
}
// This does custom data preprocessing for the flight data.
// Modified from Crossfilter example code: https://github.com/square/crossfilter/blob/gh-pages/index.html#L231
function FlightsPreprocessor() {
var my = new ChiasmComponent();
my.when("dataIn", function (dataIn){
my.dataOut = dataIn.map(function (d){
d.date = parseDate(d.date);
d.hour = d.date.getHours() + d.date.getMinutes() / 60;
d.delay = Math.max(-60, Math.min(149, d.delay));
d.distance = Math.min(1999, d.distance);
return d;
});
});
function parseDate(d) {
return new Date(2001,
d.substring(0, 2) - 1,
d.substring(2, 4),
d.substring(4, 6),
d.substring(6, 8));
}
return my;
}