D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
sfuller2
Full window
Github gist
trivariate scatterplot d3
<!DOCTYPE html> <html lang = "en"> <head> <meta charset="utf-8"> <title>A scatterplot comparing population and disease count colored by disease</title> <script src = "https://d3js.org/d3.v4.min.js"></script> <style type="text/css"> </style> </head> <body> <h3> Trivariate Scatterplot of Population vs Number of Reported Diseases </h3> <script type = "text/javascript"> //Width and height" var w = 700; var h = 500; var padding = 75; var xScale = d3.scaleLinear(); var yScale = d3.scaleLinear(); var xAxis = d3.axisBottom() .scale(xScale) .ticks(7); var yAxis = d3.axisLeft() .scale(yScale) .ticks(7); //Create SVG element var svg = d3.select("body") .append("svg") .attr("width",w) .attr("height",h); var color = d3.scaleOrdinal(d3.schemeCategory10); //use ordinal color scale to assign each disease a color //converts the data to integers var rowConverter = function(d) { return { disease : d.disease, number: parseInt(d.number), population: parseInt(d.population) } } d3.csv("health.csv", rowConverter, function(data) { dataset = data; var diseases = d3.map(dataset, function(d) {return d.disease}).keys(); xScale.domain([0, d3.max(dataset, function(d) {return d.population;})]) .range([padding,w-padding * 2]); yScale.domain([0, d3.max(dataset, function(d) {return d.number;})]) .range([h-padding,padding]); svg.selectAll("circle") .data(dataset) .enter() .append("circle") .attr("cx",function(d) { return xScale(d.population); }) .attr("cy", function(d) { return yScale(d.number); }) .attr("r", function(d) { return 2; //set all points to radius 2 }) .attr("fill", function(d) { return color(d.disease); }); svg.append("g") .attr("class", "axis") .attr("transform", "translate(0," + (h-padding) + ")") .call(xAxis); svg.append("g") .attr("class", "axis") .attr("transform", "translate(" + padding + ",0)") .call(yAxis); var legend = svg.append("g") .attr("class", "legend") .attr("x", w - 200) .attr("y", 30) .attr("height", 10) .attr("width", 10); legend.selectAll("rect") .data(diseases) .enter() .append("rect") .attr("x", w-200) .attr("y", function(d,i) { return i*20; }) .attr("height", 10) .attr("width", 10) .attr("fill", function(d) { return color(d); }); legend.selectAll("text") .data(diseases) .enter() .append("text") .text(function(d) { console.log(d); return d; }) //.attr("text-anchor", "middle") .attr("x", w-180) .attr("y", function(d,i) { return i*20 + 10; }) .attr("font-family", "sans-serif") .attr("font-size", "11px") .attr("fill", "black"); svg.append("text") .attr("transform", "translate (" + 15 + "," + (h/2) + ") rotate(-90)") .attr("text-anchor", "middle") .text("Disease Count") .attr("fill", "black"); svg.append("text") .attr("x", w/2 - 20) .attr("y", h - 10) .attr("text-anchor", "middle") .text("Population") .attr("fill", "black"); }); </script> </body> </html>