Skip to content

Instantly share code, notes, and snippets.

@mbostock
Last active February 9, 2016 01:30
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save mbostock/3305515 to your computer and use it in GitHub Desktop.
Multi-Value Maps
license: gpl-3.0

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.

<!DOCTYPE html>
<meta charset="utf-8">
<style>
circle {
fill-opacity: .1;
stroke: #000;
}
</style>
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
var width = 960,
height = 500;
// Setting two constant attributes.
var svg = d3.select("body").append("svg")
.attr({width: width, height: height});
// Setting three attributes as functions of data.
svg.selectAll("circle")
.data(d3.range(10))
.enter().append("circle")
.attr({
cx: function() { return Math.random() * width; },
cy: function() { return Math.random() * height; },
r: function() { return 100 + Math.random() * 100; }
});
// Setting attributes and styles.
svg.append("text")
.attr({x: width / 2, y: height / 2, dy: ".35em"})
.style({"text-anchor": "middle"})
.text("Hello, multi-value maps!");
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment