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>");
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
)])
25 // Generate a histogram using twenty uniformly-spaced bins.
26 var data
= d3
.layout
.histogram()
30 var y
= d3
.scale
.linear()
31 .domain([0, d3
.max(data
, function(d
) { return d
.y
; })])
34 var xAxis
= d3
.svg
.axis()
38 var svg
= d3
.select("#"+div_id
).append("svg")
40 .attr("width", width
+ margin
.left
+ margin
.right
)
41 .attr("height", height
+ margin
.top
+ margin
.bottom
)
44 .attr("transform", "translate(" + margin
.left
+ "," + margin
.top
+ ")");
46 var bar
= svg
.selectAll(".bar")
51 .attr("transform", function(d
) { return "translate(" + x(d
.x
) + "," + y(d
.y
) + ")"; });
54 .attr("id", "rect_id")
56 .attr("width", (x
.range()[1] - x
.range()[0]) / 20 )
57 .attr("height", function(d
) { return height
- y(d
.y
); });
60 .attr("id", "text_id")
63 .attr("x", ((x
.range()[1] - x
.range()[0]) / 20) / 2)
64 .attr("text-anchor", "middle")
65 .text(function(d
) { return formatCount(d
.y
); });
69 .attr("class", "x axis")
70 .attr("transform", "translate(0," + height
+ ")")
76 function identical_check(array
) {
77 for(var i
= 0; i
< array
.length
- 1; i
++) {
78 if(array
[i
] != array
[i
+1]) {