topical media & game development
mobile-data-circle-06.htm / htm
<script src="http://d3js.org/d3.v3.min.js"></script>
<link rel="stylesheet" type="text/css" href="mobile-data-circle-style-d3.css">
<script type="text/javascript">
data
var data = [32, 57, 112],
dataEnter = data.concat(293),
dataExit = data.slice(0, 2),
w = 360,
h = 180,
x = d3.scale.ordinal().domain([57, 32, 112]).rangePoints([0, w], 1),
y = d3.scale.ordinal().domain(data).rangePoints([0, h], 2);
</script>
<p>There’s a second argument to each function you can use: it specifies the <em>index</em> of the element within its selection. This is a <a href="http://en.wikipedia.org/wiki/Zero-based_numbering">zero-based</a> index, and it’s useful for computing offsets or as a simple way of identifying individual elements. The argument is optional; if you don’t specify it when declaring your function, it will be ignored. For example:</p>
<div class="chart" id="chart-6b">
<pre class="code">circle.attr("cx", function(d, i) {
return i * 100 + 30;
});
</pre>
<button>run</button>
<!--
<svg width="360" height="180"><g transform="translate(180,45)"><circle class="little" r="12"></circle><text dy=".35em" text-anchor="middle">0</text></g><g transform="translate(60,90)"><circle class="little" r="12"></circle><text dy=".35em" text-anchor="middle">1</text></g><g transform="translate(300,135)"><circle class="little" r="12"></circle><text dy=".35em" text-anchor="middle">2</text></g></svg>
-->
</div>
<script type="text/javascript">
script
(function() {
var svg = d3.select("#chart-6b").append("svg")
.attr("width", w)
.attr("height", h);
select
var g = svg.selectAll("g")
.data(data)
.enter().append("g")
.attr("transform", function(d) { return "translate(" + x(d) + "," + y(d) + ")"; });
g.append("circle")
.attr("class", "little")
.attr("r", 12);
g.append("text")
.attr("dy", ".35em")
.attr("text-anchor", "middle")
.text(function(d, i) { return i; });
button
d3.select("#chart-6b button").on("click", function() {
g.attr("transform", function(d) { return "translate(" + x(d) + "," + y(d) + ")"; })
.transition()
.duration(750)
.attr("transform", function(d, i) {
return "translate(" + (i * 100 + 30) + "," + y(d) + ")"; }
);
});
})();
</script>
<p>Here we use the index <em>i</em> to position the elements sequentially only the <em>x</em>-dimension. Each element is separated by 100 pixels, with an offset of 30 pixels from the left side. In SVG, the origin is in the top-left corner.</p>
(C) Æliens
04/09/2009
You may not copy or print any of this material without explicit permission of the author or the publisher.
In case of other copyright issues, contact the author.
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-2780434-1";
urchinTracker();
</script>