Added stacked/stream/expanded chart with example

This commit is contained in:
Bob Monteverde 2012-04-03 03:19:09 -04:00
parent 4e724cf447
commit 1cfb52c7fe
4 changed files with 449 additions and 12 deletions

View File

@ -32,10 +32,17 @@ text {
nv.addGraph({
generate: function() {
var n = 10, // number of layers
m = 200, // number of samples per layer
data = stream_layers(n, m);
m = 200; // number of samples per layer
//color = d3.interpolateRgb("#aad", "#556");
var data = stream_layers(n,m).map(function(data, i) {
return {
key: 'Stream' + i,
values: data
};
});
var width = $(window).width() - 20,
height = $(window).height() - 20;

View File

@ -0,0 +1,157 @@
<!DOCTYPE html>
<meta charset="utf-8">
<link href="../src/d3.css" rel="stylesheet" type="text/css">
<style>
body {
overflow-y:scroll;
}
text {
font: 12px sans-serif;
}
</style>
<body>
<div id="chart">
<svg></svg>
</div>
<script src="../lib/d3.v2.js"></script>
<script src="../lib/jquery.min.js"></script>
<script src="../nv.d3.js"></script>
<script src="../src/nvtooltip.js"></script>
<script src="../src/models/stackedArea.js"></script>
<script src="../src/models/stackedAreaWithLegend.js"></script>
<script>
//Format A
nv.addGraph({
generate: function() {
var n = 6, // number of layers
m = 200; // number of samples per layer
//color = d3.interpolateRgb("#aad", "#556");
//format data to our liking, add keys
var data = stream_layers(n,m).map(function(data, i) {
return {
key: 'Stream' + i,
values: data
};
});
var width = $(window).width() - 20,
height = $(window).height() - 20;
var chart = nv.models.stackedAreaWithLegend()
.width(width)
.height(height)
var svg = d3.select('#chart svg')
.attr('width', width)
.attr('height', height)
.datum(data)
svg.transition().duration(500).call(chart);
return chart;
},
callback: function(graph) {
/*
graph.dispatch.on('tooltipShow', function(e) {
var offset = $('#chart').offset(),
left = e.pos[0] + offset.left,
top = e.pos[1] + offset.top,
formatterY = d3.format(",.2%"),
formatterX = function(d) {
return d3.time.format('%x')(new Date(d))
};
var content = '<h3>' + e.series.key + '</h3>' +
'<p>' +
formatterY(graph.y()(e.point)) + ' on ' + formatterX(graph.x()(e.point)) +
'</p>';
//$('#positionTest').css({'left': left, 'top': top});
nvtooltip.show([left, top], content);
});
graph.dispatch.on('tooltipHide', function(e) {
nvtooltip.cleanup();
});
*/
$(window).resize(function() {
var width = $(window).width() - 20,
height = $(window).height() - 20,
margin = graph.margin();
if (width < margin.left + margin.right + 20)
width = margin.left + margin.right + 20;
if (height < margin.top + margin.bottom + 20)
height = margin.top + margin.bottom + 20;
graph
.width(width)
.height(height);
d3.select('#chart svg')
.attr('width', width)
.attr('height', height)
.call(graph);
});
}
});
/* Inspired by Lee Byron's test data generator. */
function stream_layers(n, m, o) {
if (arguments.length < 3) o = 0;
function bump(a) {
var x = 1 / (.1 + Math.random()),
y = 2 * Math.random() - .5,
z = 10 / (.1 + Math.random());
for (var i = 0; i < m; i++) {
var w = (i / m - y) * z;
a[i] += x * Math.exp(-w * w);
}
}
return d3.range(n).map(function() {
var a = [], i;
for (i = 0; i < m; i++) a[i] = o + o * Math.random();
for (i = 0; i < 5; i++) bump(a);
return a.map(stream_index);
});
}
/* Another layer generator using gamma distributions. */
function stream_waves(n, m) {
return d3.range(n).map(function(i) {
return d3.range(m).map(function(j) {
var x = 20 * j / m - i / 3;
return 2 * x * Math.exp(-.5 * x);
}).map(stream_index);
});
}
function stream_index(d, i) {
return {x: i, y: Math.max(0, d)};
}
</script>

View File

@ -24,18 +24,25 @@ nv.models.stackedArea = function() {
function chart(selection) {
selection.each(function(data) {
//compute the data based on offset and order (calc's y0 for every point)
data = d3.layout.stack().offset(offset).order(order)(data);
// Need to leave data alone to switch between stacked, stream, and expanded
var dataCopy = JSON.parse(JSON.stringify(data));
var mx = data[0].length - 1, // assumes that all layers have same # of samples & that there is at least one layer
my = d3.max(data, function(d) {
//log(dataCopy);
dataCopy = dataCopy.map(function(series) { return series.values })
//compute the data based on offset and order (calc's y0 for every point)
//dataCopy = d3.layout.stack().offset(offset).order(order).values(function(d){ return d.values })(dataCopy);
dataCopy = d3.layout.stack().offset(offset).order(order)(dataCopy);
var mx = dataCopy[0].length - 1, // assumes that all layers have same # of samples & that there is at least one layer
my = d3.max(dataCopy, function(d) {
return d3.max(d, function(d) {
return d.y0 + d.y;
});
});
// Select the wrapper g, if it exists.
var wrap = d3.select(this).selectAll('g.d3stream').data([data]);
var wrap = d3.select(this).selectAll('g.d3stream').data([dataCopy]);
// Create the skeletal chart on first load.
var gEnter = wrap.enter().append('g').attr('class', 'd3stream').append('g');
@ -54,15 +61,25 @@ nv.models.stackedArea = function() {
.y0(function(d) { return availableHeight - d.y0 * availableHeight / my; })
.y1(function(d) { return availableHeight - (d.y + d.y0) * availableHeight / my; });
var path = g.selectAll('path').data(data);
var zeroArea = d3.svg.area()
.x(function(d) { return d.x * availableWidth / mx; })
.y0(function(d) { return availableHeight - d.y0 * availableHeight / my; })
.y1(function(d) { return availableHeight - d.y0 * availableHeight / my; })
var path = g.selectAll('path')
.data(function(d) { return d });
//.data(dataCopy);
path.enter().append('path');
path.exit().remove();
d3.transition(path.exit())
.attr('d', zeroArea)
.remove();
path
.style('fill', function(d,i){ return color[i % 10] })
.style('stroke', function(d,i){ return color[i % 10] });
.style('fill-opacity', .75)
.style('stroke-opacity', .75)
.style('fill', function(d,i){ return color[i % 10] })
.style('stroke', function(d,i){ return color[i % 10] });
d3.transition(path)
.attr('d', area);
.attr('d', area);
});
@ -88,6 +105,12 @@ nv.models.stackedArea = function() {
return chart;
};
chart.color = function(_) {
if (!arguments.length) return color;
color = _;
return chart;
};
chart.offset = function(_) {
if (!arguments.length) return offset;
offset = _;

View File

@ -0,0 +1,250 @@
nv.models.stackedAreaWithLegend = function() {
var margin = {top: 30, right: 20, bottom: 50, left: 60},
width = 960,
height = 500,
dotRadius = function() { return 2.5 },
color = d3.scale.category10().range(),
dispatch = d3.dispatch('tooltipShow', 'tooltipHide');
var x = d3.scale.linear(),
y = d3.scale.linear(),
getX = function(d) { return d.x },
getY = function(d) { return d.y },
xAxis = nv.models.xaxis().scale(x),
yAxis = nv.models.yaxis().scale(y),
legend = nv.models.legend().height(30),
controls = nv.models.legend().height(30),
stacked = nv.models.stackedArea();
var controlsData = [
{ key: 'Stacked' },
{ key: 'Stream', disabled: true },
{ key: 'Expanded', disabled: true }
];
function chart(selection) {
selection.each(function(data) {
var series = data.filter(function(d) { return !d.disabled })
//.map(function(d) { return d.values });
.reduce(function(prev, curr, index) { //sum up all the y's
curr.values.forEach(function(d,i) {
if (!index) prev[i] = {x: d.x, y:0};
prev[i].y += getY(d);
});
return prev;
}, []);
x .domain(d3.extent(d3.merge(series), getX ))
.range([0, width - margin.left - margin.right]);
//TODO: remove if stream
y .domain(stacked.offset() == 'zero' ?
d3.extent(d3.merge(series), getY ) :
[0, 1] // 0 - 100%
)
.range([height - margin.top - margin.bottom, 0]);
stacked
.width(width - margin.left - margin.right)
.height(height - margin.top - margin.bottom)
var wrap = d3.select(this).selectAll('g.wrap').data([data]);
var gEnter = wrap.enter().append('g').attr('class', 'wrap d3stackedWithLegend').append('g');
gEnter.append('g').attr('class', 'x axis');
gEnter.append('g').attr('class', 'y axis');
gEnter.append('g').attr('class', 'stackedWrap');
gEnter.append('g').attr('class', 'legendWrap');
gEnter.append('g').attr('class', 'controlsWrap');
legend.dispatch.on('legendClick', function(d,i) {
d.disabled = !d.disabled;
if (d.disabled)
d.values.map(function(p) { p._y = p.y; p.y = 0; return p });
else
d.values.map(function(p) { p.y = p._y; return p });
if (!data.filter(function(d) { return !d.disabled }).length) {
data.map(function(d) {
d.disabled = false;
d.values.map(function(p) { p.y = p._y; return p });
//wrap.selectAll('.series').classed('disabled', false);
return d;
});
}
selection.transition().call(chart);
});
controls.dispatch.on('legendClick', function(d,i) {
if (!d.disabled) return;
controlsData = controlsData.map(function(s) {
s.disabled = true;
return s;
});
d.disabled = false;
switch (d.key) {
case 'Stacked':
stacked.style('stack');
break;
case 'Stream':
stacked.style('stream');
break;
case 'Expanded':
stacked.style('expand');
break;
}
selection.transition().call(chart);
});
/*
legend.dispatch.on('legendMouseover', function(d, i) {
d.hover = true;
selection.transition().call(chart)
});
legend.dispatch.on('legendMouseout', function(d, i) {
d.hover = false;
selection.transition().call(chart)
});
stacked.dispatch.on('pointMouseover.tooltip', function(e) {
dispatch.tooltipShow({
point: e.point,
series: e.series,
pos: [e.pos[0] + margin.left, e.pos[1] + margin.top],
seriesIndex: e.seriesIndex,
pointIndex: e.pointIndex
});
});
stacked.dispatch.on('pointMouseout.tooltip', function(e) {
dispatch.tooltipHide(e);
});
*/
//TODO: margins should be adjusted based on what components are used: axes, axis labels, legend
margin.top = legend.height();
var g = wrap.select('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
legend.width(width/2 - margin.right);
controls.width(260);
g.select('.legendWrap')
.datum(data)
.attr('transform', 'translate(' + (width/2 - margin.left) + ',' + (-margin.top) +')')
.call(legend);
g.select('.controlsWrap')
.datum(controlsData)
.attr('transform', 'translate(0,' + (-margin.top) +')')
.call(controls);
var stackedWrap = g.select('.stackedWrap')
.datum(data);
//.datum(data.filter(function(d) { return !d.disabled }))
d3.transition(stackedWrap).call(stacked);
xAxis
.domain(x.domain())
.range(x.range())
.ticks( width / 100 )
.tickSize(-(height - margin.top - margin.bottom), 0);
g.select('.x.axis')
.attr('transform', 'translate(0,' + y.range()[0] + ')');
d3.transition(g.select('.x.axis'))
.call(xAxis);
yAxis
.domain(y.domain())
.range(y.range())
.ticks( stacked.offset() == 'wiggle' ? 0 : height / 36 )
.tickSize(-(width - margin.right - margin.left), 0)
.tickFormat(stacked.offset() == 'zero' ? d3.format(',2f') : d3.format('%')); //TODO: stacked format should be set by caller
d3.transition(g.select('.y.axis'))
.call(yAxis);
});
return chart;
}
chart.dispatch = dispatch;
chart.x = function(_) {
if (!arguments.length) return getX;
getX = _;
stacked.x(_);
return chart;
};
chart.y = function(_) {
if (!arguments.length) return getY;
getY = _;
stacked.y(_);
return chart;
};
chart.margin = function(_) {
if (!arguments.length) return margin;
margin = _;
return chart;
};
chart.width = function(_) {
if (!arguments.length) return width;
width = _;
return chart;
};
chart.height = function(_) {
if (!arguments.length) return height;
height = _;
return chart;
};
chart.dotRadius = function(_) {
if (!arguments.length) return dotRadius;
dotRadius = d3.functor(_);
stacked.dotRadius = _;
return chart;
};
// Expose the x-axis' tickFormat method.
//chart.xAxis = {};
//d3.rebind(chart.xAxis, xAxis, 'tickFormat');
chart.xAxis = xAxis;
// Expose the y-axis' tickFormat method.
//chart.yAxis = {};
//d3.rebind(chart.yAxis, yAxis, 'tickFormat');
chart.yAxis = yAxis;
return chart;
}