D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
jjcruzhernandez
Full window
Github gist
ScatterPlotTrivariate_D3
<!-- Used online example to help with legend https://bl.ocks.org/mbostock/3887118 --> <!DOCTYPE html> <meta charset="utf-8"> <style> /* set the CSS */ </style> <body> <!-- load the d3.js library --> <script src="https://d3js.org/d3.v4.min.js"></script> <script> // set the dimensions and margins of the graph var margin = {top: 50, right: 250, bottom: 100, left: 100}, width = 960 - margin.left - margin.right, height = 500 - margin.top - margin.bottom; // set X and Y axis var x = d3.scaleLinear() .range([0, width]); var y = d3.scaleLinear() .range([height, 0]); // set color func var color = d3.scaleOrdinal(d3.schemeCategory20); var valueline = d3.line() .x(function(d) {return x(d.Robbery);}) .y(function(d) {return y(d.Assault);}); // create svg var svg = d3.select("body").append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); // get data d3.csv("crime3.csv", function(error, data) { if (error) throw error; // format data data.forEach(function(d) { d.Robbery = +d.Robbery; d.Assault = +d.Assault; }); console.log(data); // Scale the range of the data for X and Y axis x.domain(d3.extent(data, function(d) { return d.Robbery; })); y.domain(d3.extent(data, function(d) { return d.Assault; })); // Add the scatterplot svg.selectAll("dot") .data(data) .enter().append("circle") .attr("r", 5) .attr("cx", function(d) { return x(d.Robbery); }) .attr("cy", function(d) { return y(d.Assault); }) .style("fill", function(d){ return color(d.Department); }); // add the x-axis svg.append("g") .attr("transform", "translate(0," + height + ")") .call(d3.axisBottom(x)); // add x-axis label svg.append("text") .attr("text-anchor", "end") .attr("x", width/2) .attr("y", height + 50) .text("# Robbery"); // add y-axis svg.append("g") .call(d3.axisLeft(y)); //add y-axis label svg.append("text") .attr("transform", "rotate(-90)") .attr("x",0 - (height / 2)) .attr("y", 0 - margin.left + 20) .attr("dy", "1em") .style("text-anchor", "middle") .text("# Assault"); //adding title svg.append("text") .attr("text-anchor", "end") .attr("x", width/2 + 50) .attr("y", -15) .text("Alabaster Assault v Robbery"); var legend = svg.selectAll('legend') .data(color.domain()) .enter() .append('g') .attr('class', 'legend') .attr('transform', function(d,i){ return 'translate(0,' + i * 20 + ')'; }); //cretaing legend legend.append('rect') .attr('x', width + 20) .attr('width', 18) .attr('height', 18) .style('fill', color); legend.append('text') .attr('x', width + 40) .attr('y', 9) .attr('dy', '.35em') .style('text-anchor', 'start') .text(function(d){ return d; }); }); </script> </body>
https://d3js.org/d3.v4.min.js