Last active
December 15, 2015 23:28
-
-
Save trinary/5340127 to your computer and use it in GitHub Desktop.
d3 ML post draft
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Hello all! | |
I'd like to announce and bring your attention to a d3 extension: d3-transform. It's a simple API wrapping the creation and composition of functions to set the "transform" SVG attribute. You can find the source and some examples here: https://github.com/trinary/d3-transform | |
I found myself doing a lot of clumsy string manipulation to set transform attributes nearly every time I used d3, so I wrote an initial implementation of a transform API that added translate(), rotate(), etc functions to d3.selection. However, there were a number of drawbacks to this approach. More work would be required to use these functions in transitions, composition and reuse wouldn't be available, and so on. | |
After discussing it a bit in the #d3js IRC channel, Spiros Eliopoulos (https://twitter.com/seliopou, https://github.com/seliopou) wrote an implementation of the same idea as a separate object, d3.svg.transform. | |
Creating a transform function looks like this (from the README): | |
var transform = d3.svg.transform() | |
.translate(function(d) { return [20, d.x * 10]; }) | |
.rotate(40) | |
.scale(function(d) { return d.size }); | |
One can then use this function to set the transform attribute: | |
d3.selectAll(".x").enter() | |
.data([{x:10,size:5],[{x:20,size:2}]) | |
.append("g") | |
.attr("transform",transform); | |
For unchanging values, you can just pass in the parameters of each transform operation as arguments. For dynamic parameters, pass in a function that returns an array of parameters to the transform operation. You can reuse it, pass it around, and compose it with other d3.svg.transform objects by passing an existing transformation into the d3.svg.transform() function: | |
var transform1 = d3.svg.transform() | |
.translate(10,20); | |
var transform2 = d3.svg.transform(transform1) | |
.scale(function(d) { return [d.size];}) | |
This lets you keep different parts of a transformation separate and re-useable, and extend them to add further transformation operations. | |
I think this adds a nice interface to what is very frequently an awkward but necessary step in constructing an SVG visualization, so I'd love for people to try it out. Feedback and comments are much appreciated. If you spot something you want changed or added, open an issue on GitHub! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment