D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
rdbcasillas
Full window
Github gist
d3 scatterplots for breast cancer and iris datasets
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <script src="https://d3js.org/d3.v4.min.js"></script> <title>Basic Scatter Plot</title> <style> #svg2 { float: right; border: 1px solid black; } #svg1 { border: 1px solid black; } </style> </head> <body> <svg id="svg1" width="600" height="300"></svg> <svg id="svg2" width="600" height="300"></svg> <script> const svg = d3.select('#svg1'); const svg2 = d3.select('#svg2'); // capture width and height of the svg const width = svg.attr('width'); const height = svg.attr('height'); // create a margin object with left, right, top and bottom attributes const margin = { left: 20, right: 20, top: 20, bottom: 20 }; // use the margin object to create compressed width & height of g elements. const innerWidth = width - margin.left - margin.right const innerHeight = height - margin.top - margin.bottom // define x-axis and y-axis values for both scatterplots const xValue = d => d.Age; const yValue = d => d.Nodes; const x2Value = d => d.sepalLength; const y2Value = d => d.petalLength; const xScale = d3.scaleLinear(); const yScale = d3.scaleLinear(); // Create g elements inside svgs and shift them 20px inside from left and top. const g = svg.append('g') .attr('transform', `translate(${margin.left}, ${margin.top})`); const g2 = svg2.append('g') .attr('transform', `translate(${margin.left}, ${margin.top})`); // Make sure datasets have numeric values const row = d => { d.Age = +d.Age; d.Nodes = +d.Nodes; d.Status = +d.Status return d; }; const row2 = d => { d.petalLength = +d.petalLength; d.petalWidth = +d.petalWidth; d.sepalLength = +d.sepalLength; d.sepalWidth = +d.sepalWidth; console.log(d); return d; }; d3.csv('haberman.csv', row, data => { // for scatterplot scales, we use g elements width and height & forget about svg element attributes xScale .domain(d3.extent(data, xValue)) .range([0, innerWidth]); yScale .domain(d3.extent(data, yValue)) .range([innerHeight, 0]); g.selectAll('circle').data(data) .enter().append('circle') .attr('cx', d => xScale(xValue(d))) .attr('cy', d => yScale(yValue(d))) .attr('r', 5) .attr('opacity', 0.6) .attr('fill', function(d) { if (d.Status == 1) { return "green"; } else return "red"; }); }); d3.csv('iris.csv', row2, data2 => { xScale .domain(d3.extent(data2, x2Value)) .range([0, innerWidth]); yScale .domain(d3.extent(data2, y2Value)) .range([innerHeight, 0]); g2.selectAll('circle').data(data2) .enter().append('circle') .attr('cx', d => xScale(x2Value(d))) .attr('cy', d => yScale(y2Value(d))) .attr('fill', function(d){ if (d.species=="Iris-setosa"){ return "green"; } else if(d.species=="Iris-versicolor"){ return "purple"; } else { return "orange";} }) .attr('r', 5); }); </script> </body> </html>
https://d3js.org/d3.v4.min.js