Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
NVD3 Stacked Area Chart using CartoDBs SQL API
<!doctype html>
<meta charset="UTF8">
<title>Tornadoes total versus max damage</title>
<meta name = "viewport" content = "initial-scale = 1, user-scalable = no">
<script src=""></script>
<link rel="stylesheet" href="">
<script src="" charset="utf-8"></script>
<script src=""></script>
#chart {
height: 400px;
<div id="chart"><svg></svg></div>
var sql = cartodb.SQL({ user: 'andrew' });
sql.execute("SELECT date_part('Month', as month, count(*) total, sum(damage) damage FROM tornados t GROUP BY date_part('Month', ORDER BY date_part('Month', ASC").done(function(data) {
var total = [];
var damage = [];
for (i in data.rows){
total.push([data.rows[i].total, data.rows[i].month])
damage.push([data.rows[i].damage, data.rows[i].month])
var stackedChartData = [
key: "Damage",
values: damage
key: "Total",
values: total
nv.addGraph(function() {
var chart = nv.models.stackedAreaChart()
.margin({right: 100})
.x(function(d) { return d[1] }) //We can modify the data accessor functions...
.y(function(d) { return d[0] }) // case your data is formatted differently.
.useInteractiveGuideline(true) //Tooltips which show all data points. Very nice!
.rightAlignYAxis(true) //Let's move the y-axis to the right side.
.showControls(true) //Allow user to choose 'Stacked', 'Stream', 'Expanded' mode.
//Format x-axis labels with custom function.
.tickFormat(function(d) {
var monthNameFormat = d3.time.format("%B");
console.log(monthNameFormat(new Date(2014, d, 0)));
//return (self.chartMap) ? self.chartMap.get(id) : id;
return monthNameFormat(new Date(2014, d, 0))
.tickFormat(d3.format(',.f'));'#chart svg')
return chart;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment