D3 Tips and Tricks v4

Friday, 11 January 2013

Change a line chart into a scatter plot with d3.js

The following post is a portion of the D3 Tips and Tricks document which it free to download. To use this post in context, consider it with the others in the blog or just download the pdf  and / or the examples from the downloads page:-)

Confession time.

I didn't actually intend to add in a section with a scatter plot in it for its own sake because I thought it would be;
  1. tricky
  2. not useful
  3. all of the above
I was wrong on all counts.

I did want to have a scatter plot, because I wanted to display tool tips, but this is too neat to ignore.

It was literally a 5 minute job, 3 minutes of which was taken up by going to the d3 gallery on the wiki (https://github.com/mbostock/d3/wiki/Gallery) and ogling at the cool stuff there before snapping out of it and going to the scatter plot example (http://bl.ocks.org/3887118).

All you need to so is take the simple graph example file and slot the following block in between the 'Add the valueline path' and the 'add the x axis' blocks.
        .attr("r", 3.5)
        .attr("cx", function(d) { return x(d.date); })
        .attr("cy", function(d) { return y(d.close); });
And you will get...
Now I deliberately put the dots after the line in the drawing section, because I thought they would look better, but you could put the block of code before the line drawing block to get the following effect;
(just trying to reinforce the concept that 'order' matters when drawing objects :-)).

You could of course just remove the line block all together...

But in my humble opinion it looses something.

So what do the individual lines in the scatter plot block of JavaScript do?

The first line (svg.selectAll("dot")) essentially provides a suitable grouping label for the svg circle elements that will be added. The next line associates the range of data that we have to the group of elements we are about to add in.

Then we add a circle for each data point (.enter().append("circle")) with a radius of 3.5 pixels (.attr("r", 3.5)) and appropriate x (.attr("cx", function(d) { return x(d.date); })) and y (.attr("cy", function(d) { return y(d.close); });) coordinates.

There is lots more that we could be doing with this piece of code (check out the scatter plot example (http://bl.ocks.org/3887118)) including varying the colour or size or opacity of the circles depending on the data and all sorts of really neat things, but for the mean time, there we go. scatter plot!

I've placed a copy of the file for drawing the scatter plot into the downloads section on d3noob.org with the general examples as simple-scatterplot.html.

The above description (and heaps of other stuff) is in the D3 Tips and Tricks document that can be accessed from the downloads page of d3noob.org.

1 comment: