Skip to content

Instantly share code, notes, and snippets.

@alexanderjfink
Last active August 29, 2015 14:14
Show Gist options
  • Save alexanderjfink/25b76c8ec8911a480b70 to your computer and use it in GitHub Desktop.
Save alexanderjfink/25b76c8ec8911a480b70 to your computer and use it in GitHub Desktop.
Browser-based Data Manipulation with Miso.Dataset - Step 3
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chart.js</title>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.1/Chart.min.js"></script>
</head>
<body>
<div class="container">
<!-- Need to create a canvas for our chart -->
<canvas id="myChart" width="500" height="500"></canvas>
<script src="miso.ds.deps.0.4.1.js"></script>
<script>
/*
Use Miso.Dataset (like data.table in R or panda data.frame in python) to create a dataset
that can be manipulated in JavaScript. This action is necessary to process the data.
*/
var ds = new Miso.Dataset({
// Grab our dataset, specify a delimiter
url: 'VLSSpercapita.csv',
delimiter: ','
});
// Actually fetches the dataset from server, success callback runs our visualization
ds.fetch({
success: function() {
// Output to the browser console to see if our data frame got created
console.log("Available Columns: " + this.columnNames());
console.log("There are " + this.length + " rows");
// Create a new dataset with Miso.Dataset grouping by Region and including the Dollars column
barData = this.groupBy("Region", ["Dollars"], {
// get us some avg dollars by region
// this method executes on each of the grouped by columns as a grouped array
method: function(array) {
return _.reduce(array, function(memo, num) {
return memo + num;
}, 0) / array.length;
}
});
// This shows us what order our columns are in...
console.log(barData.column("Region").data);
// Let's see if our new grouping worked
console.log(barData.column("Dollars").data);
// Use our newly created groupings to draw with Chart.js
var data = {
labels: ["Northern Uplands", "Red River Delta", "North Coast", "Central Coast", "Central Highlands", "South East", "Mekong Delta"],
datasets: [
{
label: "Dollars",
fillColor: "rgba(151,187,205,0.5)",
strokeColor: "rgba(151,187,205,0.8)",
highlightFill: "rgba(151,187,205,0.75)",
highlightStroke: "rgba(151,187,205,1)",
data: barData.column("Dollars").data
}
]
};
var ctx = document.getElementById("myChart").getContext("2d");
var myNewChart = new Chart(ctx).Bar(data);
}
});
</script>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment