D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
sxywu
Full window
Github gist
Metis Class 3 Starter Block
Built with
blockbuilder.org
<script src="https://d3js.org/d3.v4.min.js"></script> <style type="text/css"> /*css to go here*/ svg { border:1px solid #f0f; } </style> <body></body> <script> // properties var margin = {top: 20, right: 20, bottom: 20, left: 20}; var width = 800 - margin.left - margin.right; var height = 600 - margin.top - margin.bottom; 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] + ')'); d3.csv('barleyfull.csv', function(err, response) { if (err) { console.log(err); return; } response.forEach(function(d) { // is this what we wanted to do? d.yield = +d.yield; }); // create scales var minMaxY = d3.extent(response, function(d) {return d.yield}); console.log(minMaxY) var yScale = d3.scaleLinear() .domain(minMaxY) // right now minMaxY is [2.9, 75.5] // so you want 2.9 to be mapped to height, 75.5 to 0 .range([height, 0]); // for the x's domain, we want to get all the sites // this will give us ALL the sites // but what is nice is that d3 scale will automatically unique it for us var xDomain = response.map(function(d) {return d.site}); // let me do the x scale, since we've never seen it before // we'll use a subset of ordinal scale called **scale band** // scale band takes as domain a set of categories (sites) // and returns a range that's continuous which is nice var xScale = d3.scaleBand() .domain(xDomain) .rangeRound([0, width]); var colorScale = d3.scaleOrdinal(d3.schemeCategory20); // now let's filter like missy is saying // filter is like map, so capture the result in a variable var filteredData = response.filter(function(d) { // make sure this is string (if we had converted to int // earlier, this should be int) return d.year === '1927'; }); // select container, add child elements to it // svg is main container, how to draw circles? var circles = svg.selectAll('circle') .data(filteredData) .enter().append('circle') .attr('r', 5) .attr('cy', function(d) {return yScale(d.yield);}) .attr('cx', function(d) {return xScale(d.site);}) .attr('fill', function(d) {return colorScale(d.gen);}); }); </script>
https://d3js.org/d3.v4.min.js