Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use d3 classed selection to have name as function

I am using d3 classed selections and in first parameter, instead of a string, I want to use a function that will returns class name.

selection.classed(name[, value])

I understand I can do the same using .attr() as mentioned here, but I want to be able to do the same using classed.

How can I do this?

like image 702
Priyanka dudani Avatar asked Jul 03 '13 15:07

Priyanka dudani


People also ask

How do you use d3 select this?

select() function in D3. js is used to select the first element that matches the specified selector string. If any element is not matched then it returns the empty selection. If multiple elements are matched with the selector then only the first matching element will be selected.

What do the select () and selectAll () functions in d3 do?

d3. select selects the first matching element whilst d3. selectAll selects all matching elements. Both functions take a string as its only argument.

What is attr in d3?

attr() function is used to set the attribute of the element that is selected. The name of the attribute and value of the attributes are to be set using this function.


2 Answers

The class name you provide there needs to be fixed, i.e. you cannot have something like function(d) { return d; }. If you need the class name to be determined by the data, you need to use .attr("class", ...).

If you're worried about overwriting existing class names, note that you can retrieve and prepend those as follows.

.attr("class", function(d) { return d3.select(this).attr("class") + " " + d; })
like image 78
Lars Kotthoff Avatar answered Oct 06 '22 00:10

Lars Kotthoff


I encountered a similar problem in which I wanted to add one class if a property on my datum was true and a different class if the property was false:

selection.classed('class-one', function(d) { return d.property; })
    .classed('class-two', function(d) { return d.property; });

If you have a small number of classes to add then something like this might be worth considering.

like image 43
bm1729 Avatar answered Oct 06 '22 00:10

bm1729