I'm currently using D3.js and have come across a problem that I just can't seem to solve.
I have a CSV that has a column named "Set" and a column named "Year". I want to pull the values from these columns and use them as class names. This is what I currently have...
var circle = svg.selectAll("circle") .data(data) .enter() .append("circle") .attr("class", function(d) { if (d["Set"] == 1) { return "set-1"; } if (d["Set"] == 2) { return "set-2"; } });
This works perfectly fine and gives each data-point a class name. When I try the following however, the "Set" class names are over written by the "Year" class names.
var circle = svg.selectAll("circle") .data(data) .enter() .append("circle") .attr("class", function(d) { if (d["Set"] == 1) { return "set-1"; } if (d["Set"] == 2) { return "set-2"; } .attr("class", function(d) { if (d["Year"] == 2012) { return "2012"; } if (d["Year"] == 2013) { return "2013; } });
How can this code be rectified so that it adds on additional class names as opposed to over-writing them.
Hope someone can help.
To add multiple classes to an element, select the element and pass multiple classes to the classList. add() method, e.g. box. classList. add('bg-blue', 'text-white') .
d3. select selects the first matching element whilst d3. selectAll selects all matching elements. Both functions take a string as its only argument.
each() function in D3. js is used to call the particular function for each selected HTML elements. In function datum(d) and index(i) are given as the parameters.
There is an alternative approach that can be useful. You can assign or remove classes from an element using selection.classed('class-name', true)
or selection.classed('class-name', false)
:
var circle = svg.selectAll("circle") .data(data) .enter() .append('circle') .classed('2012', function(d) { return d['Year'] === 2012; }) .classed('2013', function(d) { return d['Year'] === 2013; }) .classed('set-1', function(d) { return d['Set'] === 1; }) .classed('set-2', function(d) { return d['Set'] === 2; });
I prefer this way because you can remove the classes from an element using the same syntax.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With