Last active
April 8, 2018 21:57
-
-
Save heymatthenry/2090a58ff61d6e2975ac2c6d2946d43a to your computer and use it in GitHub Desktop.
Simple histogram to get the hang of d3's histogram layout method
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import * as d3 from 'd3'; | |
| let normals = [] | |
| for (let i = 0; i < 10000; i++) normals.push(d3.randomNormal()()) | |
| const drawingArea = { w: 800, h: 600 } | |
| const margin = { top: 20, right: 20, bottom: 20, left: 20 } | |
| const binWidth = 10 | |
| const x = d3.scaleLinear() | |
| .domain(d3.extent(normals)) | |
| .range([0, drawingArea.w - margin.left - margin.right]) | |
| const xAxis = d3.axisBottom(x) | |
| .ticks(binWidth) | |
| const hist = d3.histogram() | |
| .domain(x.domain()) | |
| .thresholds(x.ticks(binWidth)) | |
| .value(d => d) | |
| const histData = hist(normals) | |
| const y = d3.scaleLinear() | |
| .domain(d3.extent(histData, d => d.length)) | |
| .range([drawingArea.h - margin.top - margin.bottom, 0]) | |
| const svg = d3.select("body") | |
| .append("svg") | |
| .attr("width", drawingArea.w) | |
| .attr("height", drawingArea.h) | |
| svg.append("g") | |
| .attr("class", "x axis") | |
| .attr("transform", `translate(0, ${drawingArea.h - margin.top - margin.bottom})`) | |
| .call(xAxis) | |
| svg.selectAll("rect.bar") | |
| .data(histData) | |
| .enter() | |
| .append("rect") | |
| .attr("class","bar") | |
| .attr("x", d => x(d.x0)) | |
| .attr("y", d => y(d.length)) | |
| .attr("width", d => drawingArea.w / histData.length) | |
| .attr("height", d => drawingArea.h - y(d.length) - margin.top - margin.bottom) | |
| .style("fill", "#d3d3d3") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment