Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you set style in d3 via something like foo.style({color:blah, background:blah})?

Tags:

d3.js

I am going to set various css styles on an svg element, and was thinking I could do something like

d3.selectAll(".whatever")
   .style(function(d) { return {"color":getColor(d), "background":getBackground(d)}});

Now, this doesn't work, but I'm wondering if I can do something similar to centralize setting overall style properties rather than set style properties individually.

Note: as Ray suggested, you can do something like this (I'm assuming you've already got data attached to the nodes):

d3.selectAll(".whatever")
  .attr("style",function(d) {
     return cssStyleStringYouWantToUse(d);
  });
like image 535
user655489 Avatar asked May 25 '14 21:05

user655489


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 is the correct syntax to draw a circle in D3?

var circle = d3. selectAll("circle"); With a selection, we can make various changes to selected elements.

What is SVG in D3?

SVG stands for Scalable Vector Graphics. SVG is an XML-based vector graphics format. It provides options to draw different shapes such as Lines, Rectangles, Circles, Ellipses, etc. Hence, designing visualizations with SVG gives you more power and flexibility.

What is append in D3?

append() function is used to append a new element to the HTML tag name as given in the parameters to the end of the element. If the type that is given is a function then it must be evaluated for each element that is in the selection. Syntax: selection.


2 Answers

Only works on D3 v3:
To quote the documentation:

If you want to set several style properties at once, use an object literal like so:

selection.style({'stroke': 'black', 'stroke-width': 2})

This isn't possible with functions though, so in your case you still have to use the "long form".

like image 110
Lars Kotthoff Avatar answered Oct 17 '22 12:10

Lars Kotthoff


You can specify a separate function for each style name in the style literal, like so:

d3.selectAll(".whatever").style({
    color: function(d) { return getColor(d); },
    background: function(d) { return getBackground(d); }
});
like image 23
Ray Waldin Avatar answered Oct 17 '22 12:10

Ray Waldin