D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
dukevis
Full window
Github gist
Scatter With Labels
<!DOCTYPE html> <html lang="en"> <head> <style type="text/css"> .axis path, .axis line{ fill: none; stroke: black; shape-rendering: crispEdges; } .axis text{ font-family:sans-serif; font-size: 11px; } </style> <meta charset="utf-8"> <title>Title Here</title> <script type="text/javascript" src="../d3.v3/d3.v3.js"></script> </head> <body> <script type="text/javascript"> var dataset; var points; var w=1200; var h=525; d3.csv("nutrition.csv", function(data){ dataset=data; makePoints(); scatter(); }); var svg = d3.select("body").append("svg").attr("width",w).attr("height",h); var makePoints=function(){ p=[]; for(var i =0; i<dataset.length;i++){ var item = dataset[i]; var fat = parseInt(item.fat); var cals = parseInt(item.calories); if(fat>=0&&cals>=0){ p.push([fat, cals]); } } points=p; }; var padding=30; var scatter=function(){ var xScale = d3.scale.linear() .domain([0,d3.max(points,function(d){ return d[0]; })]) .range([padding+30,w-padding]); var yScale= d3.scale.linear() .domain([0,d3.max(points,function(d){ return d[1]; })]) .range([h-padding-30,padding]); var rScale = d3.scale.linear() .domain([0,d3.max(dataset,function(d){ return d[1]; })]) .range([2,5]); var cValue = d3.scale.category10(); svg.selectAll("circle") .data(points) .enter() .append("circle") .attr("cx",function(d){ return xScale(d[0]); }) .attr("cy",function(d){ return yScale(d[1]); }) .attr("r",function(d){ return rScale(d[1])*2.5; }) .attr("fill",function(d){ return cValue(d); }); makeAxis(xScale,yScale); }; var makeAxis=function(xScale,yScale){ var xAxis = d3.svg.axis().scale(xScale).orient("bottom"); svg.append("g").attr("class","axis") .attr("transform","translate(0,"+(h-padding-15)+")") .call(xAxis); var yAxis= d3.svg.axis().scale(yScale).orient("left"); svg.append("g").attr("class","axis") .attr("transform","translate(50,0)") .call(yAxis); makeLabels(); }; var makeLabels=function(){ svg.append("text") .text("Calories per Serving") .attr("x",180) .attr("y",-7) .attr("transform",function(d){ return "rotate(90)" }); svg.append("text") .text("Grams of Fat Per Serving") .attr("x",280) .attr("y",h-8); } </script> </body> </html>