Merge pull request #5248 from solgenomics/topic/batch_update_trials
[sgn.git] / js / source / legacy / SGN / Histogram.js
blob3fe871bf8fba650d9094d9db09f0fb99befa04a8
2 //Pass an array of values e.g. ['1.01', '2', '500'] and the div_id for the div you want the histogram to appear in.
4 function plot_histogram(values, div_id) {
6 var identical = identical_check(values);
8 if (identical == true) {
9 jQuery("#"+div_id).html("<center><h3>All "+values.length+" values were the same value of "+values[0]+".</h3></center>");
10 } else {
12 // A formatter for counts.
13 var formatCount = d3.format(",.0f");
15 var div_width = document.getElementById(div_id).offsetWidth;
17 var margin = {top: 10, right: 30, bottom: 30, left: 30},
18 width = div_width - margin.left - margin.right,
19 height = 200 - margin.top - margin.bottom;
21 var x = d3.scale.linear()
22 .domain([d3.min(values),d3.max(values)])
23 .range([0, width]);
25 // Generate a histogram using twenty uniformly-spaced bins.
26 var data = d3.layout.histogram()
27 .bins(x.ticks(20))
28 (values);
30 var y = d3.scale.linear()
31 .domain([0, d3.max(data, function(d) { return d.y; })])
32 .range([height, 0]);
34 var xAxis = d3.svg.axis()
35 .scale(x)
36 .orient("bottom");
38 var svg = d3.select("#"+div_id).append("svg")
39 .attr("id", "svg_id")
40 .attr("width", width + margin.left + margin.right)
41 .attr("height", height + margin.top + margin.bottom)
42 .append("g")
43 .attr("id", "g_id")
44 .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
46 var bar = svg.selectAll(".bar")
47 .data(data)
48 .enter().append("g")
49 .attr("id", "g_id")
50 .attr("class", "bar")
51 .attr("transform", function(d) { return "translate(" + x(d.x) + "," + y(d.y) + ")"; });
53 bar.append("rect")
54 .attr("id", "rect_id")
55 .attr("x", 1)
56 .attr("width", (x.range()[1] - x.range()[0]) / 20 )
57 .attr("height", function(d) { return height - y(d.y); });
59 bar.append("text")
60 .attr("id", "text_id")
61 .attr("dy", ".75em")
62 .attr("y", 6)
63 .attr("x", ((x.range()[1] - x.range()[0]) / 20) / 2)
64 .attr("text-anchor", "middle")
65 .text(function(d) { return formatCount(d.y); });
67 svg.append("g")
68 .attr("id", "g_id")
69 .attr("class", "x axis")
70 .attr("transform", "translate(0," + height + ")")
71 .call(xAxis);
76 function identical_check(array) {
77 for(var i = 0; i < array.length - 1; i++) {
78 if(array[i] != array[i+1]) {
79 return false;
82 return true;