Dynamic properties

A fairly familiar concept for readers who have been using jQuery in the past, D3 also allows you to specify properties on elements dynamically. This is an extremely powerful and essential feature of it, as it permits you to apply different styling, positioning, and content to each data node, depending on the values that are passed along:

d3.select("body")
.selectAll("svg")
.data([4, 8, 15, 16, 23, 42])
.enter().append("circle")
.attr('cx', 200) //x offset
.attr('cy', 200) //y offset
.attr('r', function(d) {
//dynamic radius based on data
return d })
.attr('fill', function (d) {
//dynamic coloring based on data
if(d>15){
return 'green'
}else{
return 'red'
}
})

Expanding on the example from before, where multiple circle radiuses were created based on their array values, the fill color of each of those circles can be evaluated dynamically based on its value. If the circle value or radius is larger than 15, it will color in green, otherwise in  red

Despite their apparent simplicity, these functions can be surprisingly powerful.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.128.189.98