|
| 1 | +function histogramChart() { |
| 2 | + var margin = {top: 0, right: 0, bottom: 20, left: 0}, |
| 3 | + width = 960, |
| 4 | + height = 500; |
| 5 | + |
| 6 | + var histogram = d3.layout.histogram(), |
| 7 | + x = d3.scale.ordinal(), |
| 8 | + y = d3.scale.linear(), |
| 9 | + xAxis = d3.svg.axis().scale(x).orient("bottom").tickSize(6, 0); |
| 10 | + |
| 11 | + function chart(selection) { |
| 12 | + selection.each(function(data) { |
| 13 | + |
| 14 | + // Compute the histogram. |
| 15 | + data = histogram(data); |
| 16 | + |
| 17 | + // Update the x-scale. |
| 18 | + x .domain(data.map(function(d) { return d.x; })) |
| 19 | + .rangeRoundBands([0, width - margin.left - margin.right], .1); |
| 20 | + |
| 21 | + // Update the y-scale. |
| 22 | + y .domain([0, d3.max(data, function(d) { return d.y; })]) |
| 23 | + .range([height - margin.top - margin.bottom, 0]); |
| 24 | + |
| 25 | + // Select the svg element, if it exists. |
| 26 | + var svg = d3.select(this).selectAll("svg").data([data]); |
| 27 | + |
| 28 | + // Otherwise, create the skeletal chart. |
| 29 | + var gEnter = svg.enter().append("svg").append("g"); |
| 30 | + gEnter.append("g").attr("class", "bars"); |
| 31 | + gEnter.append("g").attr("class", "x axis"); |
| 32 | + |
| 33 | + // Update the outer dimensions. |
| 34 | + svg .attr("width", width) |
| 35 | + .attr("height", height); |
| 36 | + |
| 37 | + // Update the inner dimensions. |
| 38 | + var g = svg.select("g") |
| 39 | + .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); |
| 40 | + |
| 41 | + // Update the bars. |
| 42 | + var bar = svg.select(".bars").selectAll(".bar").data(data); |
| 43 | + bar.enter().append("rect"); |
| 44 | + bar.exit().remove(); |
| 45 | + bar .attr("width", x.rangeBand()) |
| 46 | + .attr("x", function(d) { return x(d.x); }) |
| 47 | + .attr("y", function(d) { return y(d.y); }) |
| 48 | + .attr("height", function(d) { return y.range()[0] - y(d.y); }) |
| 49 | + .order(); |
| 50 | + |
| 51 | + // Update the x-axis. |
| 52 | + g.select(".x.axis") |
| 53 | + .attr("transform", "translate(0," + y.range()[0] + ")") |
| 54 | + .call(xAxis); |
| 55 | + }); |
| 56 | + } |
| 57 | + |
| 58 | + chart.margin = function(_) { |
| 59 | + if (!arguments.length) return margin; |
| 60 | + margin = _; |
| 61 | + return chart; |
| 62 | + }; |
| 63 | + |
| 64 | + chart.width = function(_) { |
| 65 | + if (!arguments.length) return width; |
| 66 | + width = _; |
| 67 | + return chart; |
| 68 | + }; |
| 69 | + |
| 70 | + chart.height = function(_) { |
| 71 | + if (!arguments.length) return height; |
| 72 | + height = _; |
| 73 | + return chart; |
| 74 | + }; |
| 75 | + |
| 76 | + // Expose the histogram's value, range and bins method. |
| 77 | + d3.rebind(chart, histogram, "value", "range", "bins"); |
| 78 | + |
| 79 | + // Expose the x-axis' tickFormat method. |
| 80 | + d3.rebind(chart, xAxis, "tickFormat"); |
| 81 | + |
| 82 | + return chart; |
| 83 | +} |
0 commit comments