Skip to main content
100%

Multi-Value Maps

✓ Published0🌍 Public
Mmbostock
Last edited Feb 9, 2016
Created on Aug 9, 2012

This example demonstrates D3’s multi-value map syntax, which lets developers set multiple attributes or styles in a single call using an object literal. The visualization shows a scattered arrangement of ten semi-transparent circles placed at random positions and sizes on an SVG canvas, alongside a centered text label. The code uses `selection.attr` and `selection.style` with map arguments, and defines attribute values as constants or functions of data. It relies on d3.v3 and renders entirely through SVG elements.

AI-generated description

D3 2.10.0 adds support for multi-value maps. Where previously you might have written:

svg.attr("width", width).attr("height", height);

You can now write:

svg.attr({width: width, height: height});

The new syntax (familiar to jQuery users) is slightly more concise. Like other methods in D3, the values in the maps can be specified as constants or functions of data. Multi-value maps also provide a convenient, declarative way to share code. For example, if you have the following map:

var dotAttrs = {
  cx: function() { return Math.random() * width; },
  cy: function() { return Math.random() * height; },
  r: function() { return 100 + Math.random() * 100; }
};

You can later reference this map like so:

circle.attr(dotAttrs);

This technique is similar to creating reusable functions with selection.call.

Multi-value maps are supported on the following methods: selection.attr, selection.style, selection.classed, selection.property, selection.on, transition.attr and transition.style.

gpl-3.0 Licensed

Similar vizzes