On Github mkaemmerer / intro_to_d3
Matt Kaemmerer (mattk@spiceworks.com)
d3.select('svg') .append('circle') .attr('fill', 'steelblue') .attr('r', 100) .attr('cx', 200) .attr('cy', 150);
var options = {color: 'steelblue', r: 10, x: 20, y: 15}; d3.select('svg') .append('circle') .datum(options) .attr('fill', function(d){ return d.color; }) .attr('r', function(d){ return 10*d.r; }) .attr('cx', function(d){ return 10*d.x; }) .attr('cy', function(d){ return 10*d.y; });
var data = [ {color: 'steelblue', r: 10, x: 20, y: 15}, {color: 'crimson', r: 10, x: 60, y: 15} ]; d3.select('svg') .selectAll('circle').data(data) .enter() .append('circle') .attr('fill', function(d){ return d.color; }) .attr('r', function(d){ return 10*d.r; }) .attr('cx', function(d){ return 10*d.x; }) .attr('cy', function(d){ return 10*d.y; });
var scale = d3.scale.linear() .domain([0,1]) .range([-1, 2]); scale(0); // -1 scale(0.25); // -0.25 scale(0.5); // 0.5 scale(1.0); // 2.0
var scale = d3.scale.linear() .domain([0,1]) .range(["#ffffff", "#0000ff"]); scale(0); // #ffffff (white) scale(0.25); // #bfbfff (pale blue) scale(0.5); // #8080ff (light blue) scale(1.0); // #0000ff (blue)
var width = 700, height = 300; var data = [ {continent: "Americas", country: "United States", fertility: 1.897, mortality: 0.0071, population: 315791284}, {continent: "Americas", country: "Canada", fertility: 1.664, mortality: 0.0053, population: 34674708}, ... ]; function population(d){ return d.population; } function continent(d){ return d.continent; } function fertility(d){ return d.fertility; } function mortality(d){ return d.mortality; } function country(d){ return d.country; }; var x_scale = d3.scale.linear() .domain([0, 5]) .range([0, width]); var y_scale = d3.scale.linear() .domain([0,0.1]) .range([height, 0]); var size = d3.scale.sqrt() .domain([0, d3.max(data, population)]) .range([0, 40]) var color = d3.scale.ordinal() .domain(data.map(continent)) .range(["#4daf4a", "#FFB800", "#377eb8", "#e41a1c"]); d3.select('svg') .selectAll("circle").data(data) .enter() .append("circle") .attr("cx", function(d){ return x_scale(fertility(d)); } ) .attr("cy", function(d){ return y_scale(mortality(d)); } ) .attr("r", function(d){ return size(population(d)); } ) .attr("fill", function(d){ return color(continent(d)); } );
Source: http://www.gapminder.org/data/