Creating elements
Binding and using data: data/enter/append/attr
You’re going to use this pretty much Every. Single. Time. you make a visualization.
svg.selectAll(".dinosaur-rect") // select everything with a class of 'dinosaur-rect'
.data(dinosaurs) // attach datapoints to them
.enter() // find all of the datapoints WITHOUT rectangles
.append("rect") // add a rectangles for each of those data points
.attr("class", "dinosaur-rect") // categorize/name them as dinosaur rectangles
.attr("x", 10) // give them all the same x attribute
.attr("width", function(d) {
// give them each a different width based on their height
return widthScale(d.height);
})
You’d also be changing the y
and the height
(but this is more of an idea than an actual working example).
Creating elements NOT attached to data
To create a miscellaneous element not attached to data (very useful for legends!) you just do an .append
to push the appropriate element onto the page.
svg.append("text")
.attr("x", width / 2)
.attr("y", 10)
.attr("text-anchor", "middle")
.attr("font-size", 70)
.text("THIS IS A TITLE")