Monday, August 25, 2014

How to use the same element for different data in D3

In most of the D3 examples, data elements, usually SVG objects, are added using the selectAll() method. This quickly becomes a problem when one tries to use the same element, e.g. SVG text, for different parts of the data visualization. A simple approach is to use the class tag. For this, we use the classed() method. For the following example code:

svg.selectAll('text')
    .data(data)
  .enter().append('text')
    .attr('y', function(d){return y(d.y);})
    .attr('x', function(d){return x(d.x);})
    .text(function(d){return d.name;});

we modify it to use classes as follows:

svg.selectAll('.myclass')
    .data(data)
  .enter().append('text')
    .classed('myclass', true)
    .attr('y', function(d){return y(d.y);})
    .attr('x', function(d){return x(d.x);})
    .text(function(d){return d.name;});

Instead of selecting all the text elements with the selector selectAll(), we select all the elements with the class name myclass.

Tuesday, August 19, 2014

On the fly server with Python

Run the following command in a directory of choice to make it a local web server for testing.

python -m SimpleHTTPServer 8888
Or better yet make a shell script server.sh to run it anytime you want. This comes handy when running data visualizations using D3. As a matter of fact this is where this python command was found. Source