Sample code for a tutorial demonstrating how to create an interactive using a Google Spreadsheet as a data source.
Created
September 28, 2012 13:40
-
-
Save craig552uk/3799922 to your computer and use it in GitHub Desktop.
Blog: Google Spreadsheet Powered Interactive
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<title>My Chart</title> | |
<meta charset="utf-8"> | |
</head> | |
<body> | |
<p class="my-chart" style="text-align:center"></p> | |
<script src="/js/d3.v2.min.js"></script> | |
<script src="/js/miso.ds.deps.min.0.2.2.js"></script> | |
<script> | |
// Define Google spreadsheet as data source | |
var ds = new Miso.Dataset({ | |
key: "0AvmGs2D9eZgxdFhOTGowSFEwNHNBQno5S1Bab2FnY3c", | |
worksheet: "1", | |
importer: Miso.Importers.GoogleSpreadsheet, | |
parser: Miso.Parsers.GoogleSpreadsheet | |
}); | |
// Fetch the data | |
ds.fetch({ | |
success: function() { | |
// Extract data to array | |
var data = []; | |
this.each(function(row){ data.push(row); }); | |
// Create SVG element for chart | |
var chart = d3.selectAll('.my-chart').append('svg') | |
.attr('width', 300) | |
.attr('height', function(){ return data.length*25; }); | |
// Create a scale for the bars | |
var scale = d3.scale.linear().domain([0, ds.max("Quantity")]).range([0,150]); | |
// Create one group per data row | |
chart.selectAll('g').data(data).enter().append('g') | |
.attr('transform', function(d,i){ return "translate(0," + i*25 + ")"; }); | |
// Create rect element for bar | |
chart.selectAll('g').append('rect') | |
.attr('fill', 'blue') | |
.attr('height', 23) | |
.attr('width', function(d){ return scale(d["Quantity"]); }) | |
.attr('x', 80) | |
.attr('y', 2) | |
// Create text element for category | |
chart.selectAll('g').append('text') | |
.text(function(d){ return d["Category"]; }) | |
.attr('text-anchor', 'end') | |
.attr('height', 25) | |
.attr('x', 70) | |
.attr('y', 20) | |
// Create text element for quantity | |
chart.selectAll('g').append('text') | |
.text(function(d){ return d["Quantity"]; }) | |
.attr('height', 25) | |
.attr('x', function(d){ return scale(d["Quantity"]) + 85; }) | |
.attr('y', 20) | |
}, | |
error: function() { | |
document.getElementById('chart').innerHTML = "Could not load data."; | |
} | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment