D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
lucamerzi
Full window
Github gist
scatterplot svg w/ 2 linear scales
Built with
blockbuilder.org
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>D3 Scatter Plot</title> <script src="https://d3js.org/d3.v5.js"></script> <style> #chart{ width:800px;height:400px;background-color:#f7f7f7;margin:25px auto; } </style> </head> <body> <div id="chart"></div> <script> var data = [ [ 400, 200 ], [ 210,140 ], [ 722,300 ], [ 70,160 ], [ 250,50 ], [ 110,280 ], [ 699,225 ], [ 90, 220 ] ] var chart_width = 800 var chart_height = 400 var padding = 50 // create svg element var svg = d3.select("#chart") .append("svg") .attr("width", chart_width) .attr("height", chart_height) // create x_scale var x_scale = d3.scaleLinear() .domain([0, d3.max(data, function(d){ return d[0] })]) .range([padding, chart_width - padding * 2]) // create y scale var y_scale = d3.scaleLinear() .domain([0, d3.max(data, function(d){ return d[1] })]) .range([chart_height - padding, padding]) // create r scale // var r_scale = d3.scaleLinear() // .domain([0, d3.max(data, function(d){ // return d[1] // })]) // .range([5, 30]) // create a scale to replace r scale var a_scale = d3.scaleSqrt() .domain([0, d3.max(data,function(d){ return d[1] })]) .range([0, 25]) // create and add x_axis var x_axis = d3.axisBottom(x_scale) svg.append("g") .classed("x-axis", true) .call(x_axis) .attr("transform", `translate(0,${chart_height - padding})`) // create and add y_axis var y_axis = d3.axisLeft(y_scale) .ticks(6) svg.append("g") .classed("x-axis", true) .attr("transform", `translate(${padding},0)`) .call(y_axis) // add circles svg.selectAll("circle") .data(data) .enter() .append("circle") .attr("cx", function(d){ return x_scale(d[0]) }) .attr("cy", function(d){ return y_scale(d[1]) }) .attr("r", function(d){ return a_scale(d[1]) }) .attr("fill", "#D1AB0E") // create labels svg.append("g").selectAll("text") .data(data) .enter() .append("text") .text(function(d){ return (`x:${d[0]}; y:${d[1]}`) }) .attr("x", function(d){ return x_scale(d[0]) }) .attr("y", function(d){ return y_scale(d[1]) }) .attr("font-size", "12") </script> </body> </html>
https://d3js.org/d3.v5.js