HTML5 Data Visualizations "“ Part 3 "“ Getting Started with RaphaÃ«l
In the last part of this series we looked at building a basic graph using static SVG. This approach is a little limited in that it is painful to build up this markup on the server side. I mentioned that SVG elements are part of the DOM and this is true but it isn’t as easy to manipulate the items as you might think.
Here is some code which seems like it would add a new circle to the SVG
But if you run that on the page that we created in part 2 the expected circle doesn’t appear. What’s going on? Well even though the circle is appended to the SVG when we examine the DOM in the developer tools in Chrome. Well it is a bit weird but despite the fact that the code exists in the same document it is actually in a different name space so the circle we add is not a real SVG circle. There are some hacks to get around it listed in this great Stackoverflow question. Instead of these hacks you can use a graphing library like Raphael. Technically the e in Raphael has an umlaut on it but I say we didn’t take the birch cane out and give the Germans a right proper thrashing so they can go about inventing characters.
Jolly. good. show.
Raphael is a library for manipulating SVGs and easily creating drawings. It is great for the sorts of data visualizations we’re interested in. Let’s go about recreating out graph from part II using Raphael.
Here we’ve made use of some data which could be json sourced from the server or from some other API. We’ve also done some simple math to figure out appropriate column heights. This makes everything far moreexpandable. If we want more columns then all that is needed is to add more to the data array. In this example code we haven’t accounted for recalculating the width of the columns so this graph will become wider as more columns are added.
You might notice that the last column there is clipped. That’s because we have more columns than can be fit into the size of the SVG we created.
We can easily add labels with just one more line, in this case line 26.