Dynamically generating SVG elements

Currently, we have just enough <circle> elements to fit our data. What if we don't want to count how many elements are in the array? D3 can create elements as needed. First, remove all <circle> elements from index.html. Your <body> tag should now look as follows:

<body>
<svg></svg>
<script src="https://d3js.org/d3.v5.min.js"></script>
<script src="app.js" charset="utf-8"></script>
</body>

In app.js, go to this part of the code:

d3.selectAll('circle').data(runs)
    .attr('cy', function(datum, index){
        return yScale(datum.distance);
    });

Modify the code to create the circles:

//since no circles exist, we need to select('svg')
//so that d3 knows where to append the new circles
d3
.select('svg').selectAll('circle') .data(runs) //attach the data as before
//find the data objects that have not yet
//been attached to visual elements
.enter()
//for each data object that hasn't been attached,
//append a <circle> to the <svg> .append('circle'); d3.selectAll('circle') .attr('cy', function(datum, index){ return yScale(datum.distance); });

It should look exactly the same as before, but now circles are being created for each object in the runs array:

Here's a more in-depth explanation of what we just wrote. Take a look at the first line of the new code:

d3.select('svg').selectAll('circle')

This might seem unnecessary. Why not just do d3.selectAll('circle')? Well, at the moment, there are no circle elements. We're going to be appending circle elements dynamically, so d3.select('svg') tells D3 where to append them. We still need .selectAll('circle') though, so that when we call .data(runs) on the next line, D3 knows what elements to bind the various objects in the runs array to. But there aren't any circle elements to bind data to. That's OK..enter() finds the run objects that haven't been bound to any circle elements yet (in this case all of them). We then use .append('circle') to append a circle for each unbound run object that .enter() found.

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

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