D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
Noelfish6
Full window
Github gist
Drawing a Scatterplot
Built with
blockbuilder.org
<!DOCTYPE html> <head> <meta charset="utf-8"> <script src="https://d3js.org/d3.v4.min.js"></script> <style> .canvas{width:100%;min-height:600px;} .country circle{fill-opacity:.1;stroke:black;stroke-width:1px;} .highlight circle{stroke:red;stroke-width:2px;} .country text{font-size:10px;} .axis .tick line{stroke:rgb(150,150,150);} .axis .tick line{stroke-width:.5px;} </style> </head> <body> <div class="container"> <h1>Drawing a Scatterplot</h1> <section class="canvas" id="canvas"> </section> </div> <script> d3.csv('world_bank_1995_gdp_co2.csv',parse,function(err,rows){ var extentX = d3.extent(rows, function(d){return d.gdpPerCap}), extentY = d3.extent(rows, function(d){return d.co2PerCap}), extentPop = d3.extent(rows, function(d){return d.pop}); var scaleX = d3.scalePow().exponent(.5).domain(extentX).range([0,500]), scaleY = d3.scalePow().exponent(.5).domain(extentY).range([360,0]), scaleSize = d3.scaleSqrt().domain(extentPop).range([2,20]); var plot = d3.select('.canvas') .append('svg') .attr('width',600) .attr('height',460) .append('g'); var nodes = plot.selectAll('country') .data(rows) .enter() .append('g') .attr('class','country') .attr('transform',function(d){ return 'translate('+scaleX(d.gdpPerCap)+','+scaleY(d.co2PerCap)+')'; }) .on('click',function(d){ d3.select(this).classed('highlight',true); }); nodes.append('circle').attr('r',function(d){return scaleSize(d.pop);}); nodes.append('text').text(function(d){return d.code}); var axisX = d3.axisBottom() .scale(scaleX) .tickSize(-360); var axisY = d3.axisLeft() .scale(scaleY) .tickSize(-500); plot.append('g').attr('class','axis axis-x') .attr('transform','translate(0,'+360+')') .call(axisX); plot.append('g').attr('class','axis axis-y').call(axisY); }); function parse(d){ if(d['GDP per capita, PPP (constant 2011 international $)']=='..' || d['CO2 emissions (metric tons per capita)']=='..'){ return; } return { name:d['Country Name'], code:d['Country Code'], gdpPerCap:+d['GDP per capita, PPP (constant 2011 international $)'], co2PerCap:+d['CO2 emissions (metric tons per capita)'], pop:+d['Population, total'] } } </script> </body>
https://d3js.org/d3.v4.min.js