summaryrefslogtreecommitdiff
path: root/public/js/d3funcs.js
diff options
context:
space:
mode:
Diffstat (limited to 'public/js/d3funcs.js')
-rw-r--r--public/js/d3funcs.js88
1 files changed, 88 insertions, 0 deletions
diff --git a/public/js/d3funcs.js b/public/js/d3funcs.js
new file mode 100644
index 0000000..4fafb42
--- /dev/null
+++ b/public/js/d3funcs.js
@@ -0,0 +1,88 @@
+show_bargraph = function(datasource, title, xlab, ylab) {
+ var margin = {top: 40, right: 20, bottom: 30, left: 40},
+ width = 960 - margin.left - margin.right,
+ height = 500 - margin.top - margin.bottom;
+
+ var formatPercent = d3.format(".0%");
+
+ var x = d3.scale.ordinal()
+ .rangeRoundBands([0, width], .1);
+
+ var y = d3.scale.linear()
+ .range([height, 0]);
+
+ var xAxis = d3.svg.axis()
+ .scale(x)
+ .orient("bottom");
+
+ var yAxis = d3.svg.axis()
+ .scale(y)
+ .orient("left");
+ // .tickFormat(formatPercent);
+
+ var tip = d3.tip()
+ .attr('class', 'd3-tip')
+ .offset([-10, 0])
+ .html(function(d) {
+ return "<strong>Frequency:</strong> <span style='color:red'>" + d.y + "</span>";
+ })
+
+ var svg = d3.select("body").append("svg")
+ .attr("width", width + margin.left + margin.right)
+ .attr("height", height + margin.top + margin.bottom)
+ .append("g")
+ .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
+
+ svg.call(tip);
+
+ d3.tsv(datasource, type, function(error, data) {
+ if (error) console.warn(error);
+ x.domain(data.map(function(d) { return d.x; }));
+ y.domain([0, d3.max(data, function(d) { return d.y; })]);
+
+ svg.append("g")
+ .attr("class", "x axis")
+ .attr("transform", "translate(0," + height + ")")
+ .call(xAxis)
+ .append("text")
+ .attr("x", width / 2)
+ .attr("y", 30)
+ .style("text-anchor", "middle")
+ .text(xlab);
+
+ svg.append("g")
+ .attr("class", "y axis")
+ .call(yAxis)
+ .append("text")
+ .attr("transform", "rotate(-90)")
+ .attr("y", 6)
+ .attr("dy", ".71em")
+ .style("text-anchor", "end")
+ .text(ylab);
+
+ svg.append("text")
+ .attr("x", (width / 2))
+ .attr("y", 0 - (margin.top / 2))
+ .attr("text-anchor", "middle")
+ .style("font-size", "16px")
+ .style("text-decoration", "underline")
+ .text(title);
+
+ svg.selectAll(".bar")
+ .data(data)
+ .enter().append("rect")
+ .attr("class", "bar")
+ .attr("x", function(d) { return x(d.x); })
+ .attr("width", x.rangeBand())
+ .attr("y", function(d) { return y(d.y); })
+ .attr("height", function(d) { return height - y(d.y); })
+ .on('mouseover', tip.show)
+ .on('mouseout', tip.hide)
+
+ });
+
+ function type(d) {
+ d.y = +d.y;
+ return d;
+ }
+}