D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
akeshavan
Full window
Github gist
Step08
Built with
blockbuilder.org
<html lang="en"> <head> <title> Neurohackweek 2017 D3 Tutorial </title> <!-- Style definitions will go in the <style> tags --> <style> </style> </head> <!-- Content goes in the body --> <body> <h3> Below is a scatter plot: </h3> <svg id="scatterArea"></svg> </body> <!-- Import Javascript files here--> <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.10.0/d3.min.js"></script> <script> function randomInt(min, max){ return Math.floor(Math.random() * (max - min + 1)) + min; } function addData(){ data.push(randomInt(30,200)) //append a random number to data render(data) } function randomData(){ for (i=0; i<data.length; i++){ data[i] = randomInt(30,200) } render(data) } function removeData(){ data.pop() //remove last element render(data) } function renderAxes(data){ //define margins on the plot -- this will give room for axes labels, titles var margin = {top: 20, right: 20, bottom: 30, left: 60} // total dimensions are 500x300 var width = 500 - margin.left - margin.right var height = 300 - margin.top - margin.bottom // data struct -> x value var xValue = function(d) { return d.x;} var yValue = function(d) { return d.y;} // value -> display xScale = d3.scaleLinear().range([0, width]) yScale = d3.scaleLinear().range([height, 0]), // in SVG, y=0 is at the top, so we switch the order // now the range [0, width] maps to [0, max(data)] xScale.domain([d3.min(data, xValue), d3.max(data, xValue)]) yScale.domain([d3.min(data, xValue), d3.max(data, yValue)]) var svg = d3.select("#scatterArea") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); xAxis = d3.axisBottom(xScale) //axis object yAxis = d3.axisLeft(yScale) // x-axis svg.append("g") .attr("class", "x axis") //take X to bottom of SVG .attr("transform", "translate(0," + height + ")") .call(xAxis) // y-axis svg.append("g") .attr("class", "y axis") .call(yAxis) } var scatterData = [ {x: 0.5, y: 20}, {x: 2.1, y: 12}, {x: 1.4, y: 5.2}, {x: 2.9, y: 9.6} ] renderAxes(scatterData) </script> </html>
https://cdnjs.cloudflare.com/ajax/libs/d3/4.10.0/d3.min.js