D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
dukevis
Full window
Github gist
ClippingMask
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Title Here</title> <script type="text/javascript" src="../d3.v3/d3.v3.js"></script> <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> </head> <body> <script type="text/javascript"> var dataset; var points; var w=1200; var h=525; var padding=30; var xS; var yS; var svg = d3.select("body").append("svg").attr("width",w).attr("height",h); d3.csv("nutrition.csv", function(data){ dataset=data; makePoints(dataset); }); var makePoints=function(dataset){ 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; scatter(); }; var scatter=function(){ var xScale = d3.scale.linear() .domain([0,d3.max(points,function(d){ return d[0]; })]) .range([padding+30,w-padding*2]); 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.append("clipPath") .attr("id","chart-area") .append("rect") .attr("x",padding+20) .attr("y",padding) .attr("width",w-padding*3) .attr("height",h-padding*2) svg.append("g") .attr("id","circles") .attr("clip-path","url(#chart-area)") .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); }); var xAxis = d3.svg.axis() .scale(xScale) .orient("bottom"); var yAxis= d3.svg.axis() .scale(yScale) .orient("left"); svg.append("g") .attr("class","xaxis") .attr("transform","translate(0,"+(h-padding-15)+")") .call(xAxis); svg.append("g") .attr("class","yaxis") .attr("transform","translate(50,0)") .call(yAxis); svg.selectAll("circle") .on("click", function(){ for(var b=0;b<p.length;b++){ p[b][0]=p[b][0]*.85; p[b][1]=p[b][1]*.5; points=p; } svg.selectAll("circle") .data(points) .transition() .duration(1000) .attr("cx",function(d){ return xScale(d[0])*.85; }) .attr("cy",function(d){ return yScale(d[1])*.5; }); svg.select("xaxis") .transition() .duration(1000) .call(xAxis); svg.select("yaxis") .transition() .duration(1000) .call(yAxis); }); makeLabels(xAxis, yAxis,points); }; var makeLabels=function(xAx, yAx,p){ 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>