Skip to content

Instantly share code, notes, and snippets.

@mythmon
Forked from willkg/README.md
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mythmon/17dca7abd23b8ff7ebbd to your computer and use it in GitHub Desktop.
Save mythmon/17dca7abd23b8ff7ebbd to your computer and use it in GitHub Desktop.
Test of using input.mozilla.org and d3 and bl.ocks.org

This gist goes through the motions to see if I can get a basic block working with gists and all that.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<style>
body {
font: 10px sans-serif;
margin: 0;
}
.chart rect {
fill: steelblue;
}
.chart text {
fill: black;
font: 10px sans-serif;
}
</style>
<body>
<svg class="chart"></svg>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="main.js"></script>
</body>
</html>
"use strict";
var inputUrl = "https://input.mozilla.org/api/v1/feedback/?locales=en-US&format=json";
var width = 420,
barHeight = 20;
var x = d3.scale.linear()
.range([0, width]);
var chart = d3.select(".chart")
.attr("width", width);
d3.json(inputUrl, function(error, data) {
console.log('error', error);
console.log('data', data);
// Make an aggregator that splits data by product name, and then reduces
// the groups by counting the number of elements in it.
var aggregator = d3.nest()
.key(function(d) { return d.product = d.product || 'Unknown'; })
.rollup(function(group) { return {name: group[0].product, value: group.length}; });
// Apply the aggregator, tand then get only the values from it.
data = aggregator.map(data.results, d3.map).values();
// Sort the data descendingly by the bar length.
data.sort(function(a, b) { return d3.descending(a.value, b.value); });
console.log('data', data);
// Set the x domain (.domain is a mutator)
x.domain([0, d3.max(data, function(d) { return d.value; })]);
// Making these separate selections makes animation and changing data later
// easier.
var bars = chart.append('g').classed('bars', true)
.selectAll('rect').data(data);
var labels = chart.append('g').classed('labels', true)
.selectAll('text').data(data);
// Enter
bars.enter().append('rect');
labels.enter().append('text');
// Update
bars.attr('x', 0)
.attr('y', function(d, i) { return i * barHeight; })
.attr("width", function(d) { return x(d.value); })
.attr("height", barHeight - 1);
labels.attr("x", function(d) { return 5; })
.attr("y", function(d, i) { return (i + 0.6) * barHeight; })
.text(function(d) { return d.name + ': ' + d.value; })
.style('text-anchor', 'middle-left');
// Exit
bars.exit().remove();
labels.exit().remove();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment