D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
tovare
Full window
Github gist
Excercise 5: Cash for Care Scatterplot
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Excercise module 4</title> <script type="text/javascript" src="https://d3js.org/d3.v3.js"></script> <style type="text/css"> body{ margin-left : 4em; margin-right : 4em; } svg { background-color: white; } .axis path, .axis line { fill: none; stroke: black; shape-rendering: crispEdges; } .axis text { font-family: Arial, sans-serif; font-size: 12px; } </style> </head> <body> <h2>Cash for Care recipients</h2> <p> Number of cash for care reciptients in 2009 and 2014. Male age groups shown in blue and women in red. This is not a good encoding as is for this type of information. </p> <script type="text/javascript"> function drawYear(data,year1,year2){ var width = 500; var height = 350; var svg = d3.select("body").append("svg"); svg.attr("width",width).attr("height",height) var padding = { top: 50, right: 20, bottom: 20, left: 50 }; // Sort the data //data.sort(function(a, b) { // return d3.ascending(parseInt(a["2005"]),parseInt(b["2005"])); //}); var xScale = d3.scale.linear() .range([ padding.left, width - padding.right - padding.left ]) .domain([0, d3.max(data, function(d) { return +d[year1]; })]); var yScale = d3.scale.linear() .range([ padding.top, height - padding.bottom]) .domain([ d3.max(data, function(d) { return +d[year2]; }),0]); var xAxis = d3.svg.axis() .scale(xScale) .orient("bottom"); var yAxis = d3.svg.axis() .scale(yScale) .orient("left"); var circles = svg.selectAll("circle") .data(data) .enter() .append("circle"); circles.attr("cx", function (d) { return xScale(+d[year1]); } ) .attr("cy", function(d,i){ return yScale(+d[year2]); }) .attr("r",0.1) .attr("fill", function(d){ // Different colors for each age group if(d["Category"].indexOf("Men") > -1) return "#3182bd"; else return "#de2d26"; }) .append("title") .text(function(d){ return d["Category"]+" "+year1+": "+d[year1] + ", "+year2+": "+d[year2]; }); svg.append("g") .attr("class", "x axis") .attr("transform", "translate(" + 0 + "," + (height - padding.bottom + ")")) .call(xAxis); svg.append("g") .attr("class", "y axis") .attr("transform", "translate(" + (padding.left) + ",0)") .call(yAxis); svg.append("text") .attr("class", "x label") .attr("text-anchor", "end") .attr("x", width) .attr("y", height - 6) .text(year1); svg.append("text") .attr("class", "y label") .attr("text-anchor", "end") .attr("y", 6) .attr("dy", ".75em") .attr("transform", "rotate(-90)") .text(year2); circles.transition() .delay(function(d, i) { return i*1000 }) .duration(1000) .attr("r",10); } //Load in contents of CSV file d3.csv("Number of Cash for Care recipients by year and sex2.csv", function(data) { drawYear(data,"2009","2014"); }) </script> </body> </html>
Modified
http://d3js.org/d3.v3.js
to a secure url
https://d3js.org/d3.v3.js