Skip to content

Instantly share code, notes, and snippets.

@acouch
Created December 11, 2014 20:12
Show Gist options
  • Save acouch/813fe8b291b9d8d215e1 to your computer and use it in GitHub Desktop.
Save acouch/813fe8b291b9d8d215e1 to your computer and use it in GitHub Desktop.
NVD3 Stacked Area Chart using CartoDBs SQL API
<!doctype html>
<meta charset="UTF8">
<html>
<head>
<title>Tornadoes total versus max damage</title>
<meta name = "viewport" content = "initial-scale = 1, user-scalable = no">
<script src="http://libs.cartocdn.com/cartodb.js/v3/cartodb.js"></script>
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/nvd3/1.1.15-beta/nv.d3.min.css">
<script src="http://cdnjs.cloudflare.com/ajax/libs/d3/3.5.2/d3.js" charset="utf-8"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/nvd3/1.1.15-beta/nv.d3.js"></script>
<style>
#chart {
height: 400px;
}
</style>
</head>
<body>
<div id="chart"><svg></svg></div>
<script>
var sql = cartodb.SQL({ user: 'andrew' });
sql.execute("SELECT date_part('Month', t.date) as month, count(*) total, sum(damage) damage FROM tornados t GROUP BY date_part('Month', t.date) ORDER BY date_part('Month', t.date) ASC").done(function(data) {
console.log(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])
}
console.log(data)
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] }) //...in 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.
.transitionDuration(500)
.showControls(true) //Allow user to choose 'Stacked', 'Stream', 'Expanded' mode.
//.clipEdge(true);
//Format x-axis labels with custom function.
chart.xAxis
.tickFormat(function(d) {
console.log(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))
});
console.log(stackedChartData);
chart.yAxis
.tickFormat(d3.format(',.f'));
d3.select('#chart svg')
.datum(stackedChartData)
.call(chart);
nv.utils.windowResize(chart.update);
return chart;
});
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment