Skip to content

Instantly share code, notes, and snippets.

@louischatriot
Created May 5, 2012 11:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save louischatriot/2601663 to your computer and use it in GitHub Desktop.
Save louischatriot/2601663 to your computer and use it in GitHub Desktop.
d3 introduction code - js part
// Suppose there is currently one div with id "d3TutoGraphContainer" in the DOM
// We append a 600x300 empty SVG container in the div
var chart = d3.select("#d3TutoGraphContainer").append("svg").attr("width", "600").attr("height", "300");
// Create the bar chart which consists of ten SVG rectangles, one for each piece of data
var rects = chart.selectAll('rect').data([1 ,4, 5, 6, 24, 8, 12, 1, 1, 20])
.enter().append('rect')
.attr("stroke", "none").attr("fill", "rgb(7, 130, 180)")
.attr("x", 0)
.attr("y", function(d, i) { return 25 * i; } )
.attr("width", function(d) { return 20 * d; } )
.attr("height", "20");
// Transition on click managed by jQuery
rects.on('click', function() {
// Generate randomly a data set with 10 elements
var newData = [];
for (var i=0; i<10; i+=1) { newData.push(Math.floor(24 * Math.random())); }
// Generate a random color
var newColor = 'rgb(' + Math.floor(255 * Math.random()) +
', ' + Math.floor(255 * Math.random()) +
', ' + Math.floor(255 * Math.random()) + ')';
rects.data(newData)
.transition().duration(2000).delay(200)
.attr("width", function(d) { return d * 20; } )
.attr("fill", newColor);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment