user6665903
user6665903

Reputation:

Using objects to simplify code in d3.js

I'd like to make code easy to read. There are too duplicated methods like this.

var svg = d3.append('svg').attr(...).attr('...').attr('...').style(...).style(...);

This is a bit difficult to read so I want to simplify code.

var svg = d3.append('svg').attr({'class','test_class'},{'x','x_value'}).style({'fill','value'},{...});

Any help would be appreciated.

Upvotes: 0

Views: 170

Answers (1)

Gerardo Furtado
Gerardo Furtado

Reputation: 102174

D3 version 3.x

You can do that using D3 v3.x. Check the demo:

var svg = d3.select("body")
  .append("svg");

var data = [10, 5, 15, 20, 12, 8, 17];

var circles = svg.selectAll(".circle")
  .data(data)
  .enter()
  .append("circle");

circles.attr({
    cx: function (d,i) { return 10 + i*40; },
    cy: 50,
    r:  function (d) { return d; },
    fill: "teal"
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

D3 version 4.x

However, this will not work in the new D3 v4.x. For passing objects like that, you'll need the selection-multi:

<script src="https://d3js.org/d3-selection-multi.v1.min.js"></script>

Besides that, have in mind that you'll have to change:

  • attr must be attrs

  • style must be styles

Check the demo using v4.x:

var svg = d3.select("body")
  .append("svg");

var data = [10, 5, 15, 20, 12, 8, 17];

var circles = svg.selectAll(".circle")
  .data(data)
  .enter()
  .append("circle");

circles.attrs({
    cx: function (d,i) { return 10 + i*40; },
    cy: 50,
    r:  function (d) { return d; },
    fill: "teal"
  });
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/d3-selection-multi.v1.min.js"></script>

PS: your example of simplified code (the second one) is not a valid object (because the key/value pair is separated by comma instead of colon) or a valid array (because there is no square bracket). Thus, it should be:

.attr({'class': 'test_class', 'x': 'x_value'})

Upvotes: 2

Related Questions