D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
uptheirons78
Full window
Github gist
First ScatterPlot
Built with
blockbuilder.org
<!DOCTYPE html> <head> <meta charset="utf-8"> <script src="https://d3js.org/d3.v4.min.js"></script> <style> body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; } svg {margin-left: 100px; margin-top: 50px;} .tick line {stroke: #ccc; stroke-dasharray: 5, 5;} </style> </head> <body> <svg></svg> <script src="birthData2011.js"></script> <script> const width = 500; const height = 500; const padding = 30; //d3.extent(values) return an array of min and max values const yScale = d3.scaleLinear() .domain(d3.extent(birthData2011, d => d.lifeExpectancy)) .range([height - padding, padding]); const xScale = d3.scaleLinear() .domain(d3.extent(birthData2011, d => d.births / d.population)) .range([padding, width - padding]); const colorScale = d3.scaleLinear() .domain(d3.extent(birthData2011, d => d.population / d.area)) .range(['lightgreen', 'black']); const radiusScale = d3.scaleLinear() .domain(d3.extent(birthData2011, d => d.births)) .range([2, 40]); //create Axes and Grids const xAxis = d3.axisBottom(xScale) .tickSize(-height + 2 * padding) .tickSizeOuter(0); const yAxis = d3.axisLeft(yScale) .tickSize(-width + 2 * padding) .tickSizeOuter(0); var svg = d3.select("svg") .attr("width", width) .attr("height", height); //draw Axes svg .append('g') .attr("transform", `translate(0, ${height - padding})`) .call(xAxis); svg .append('g') .attr("transform", `translate(${padding}, 0)`) .call(yAxis); svg.selectAll('circle').data(birthData2011).enter() .append("circle") .attr("cx", d => xScale(d.births / d.population)) .attr("cy", d => yScale(d.lifeExpectancy)) .attr("r", d => radiusScale(d.births)) .attr("fill", d => colorScale(d.population / d.area)) .attr("fill-opacity", 0.8); svg .append('text') .attr('x', width / 2) .attr('y', height - padding) .attr('dy', '1.5em') .style('text-anchor', 'middle') .text('Births per Capita'); svg .append('text') .attr('x', width / 2) .attr('y', padding) .style('text-anchor', 'middle') .style('font-size', '1.5em') .style('font-weight', 'bold') .text('Data on Births by Country in 2011'); svg .append('text') .attr('transform', 'rotate(-90)') .attr('x', - height / 2) .attr('y', padding) .attr('dy', '-1.1em') .style('text-anchor', 'middle') .style('font-weight', 'bold') .text('Life Expectancy'); </script> </body>
https://d3js.org/d3.v4.min.js