Pure SVG graph builder

27 Jan 2011 Code on Github


Having worked out how to create reasonable looking buttons in an SVG (which was basically a matter of changing the cursors), I've been trying to think of ways to create an application using pure SVG. Below is graph-drawing SVG which I quickly threw together to see how far I could get rather than to actually create something worthwhile. I don't think an application like this could be useful because once the graph is drawn, there is no way to save it, and everything is lost when you refresh. However, it made me appreciate the potential of SVGs, if only I could find the right problem.

Click to add label Click to add label Add Data value

The graph-builder is pretty basic as I made it quickly. Clearly the interface is a quite clunky (I'm not sure by how much it could be improved). Given more time, a lot more functionality could be added, such as showing axis values and tick marks, and by allowing bars to represent negative numbers. However, overall, I'm pretty pleased.

One of the features I'm particularly pleased with is the alignment of the axis labels, which automatically centre no matter what the length of the text. This requires the getComputedTextLength() function, but is more complicated for the y-axis label, which also needs to be rotated about its centre. For this I learnt how to use the transform attribute and make sure the text didn't rotate out of view. When I get a moment, I'll use the text length to properly align the bar's mouseover values.

[EDIT: Using the style text-align: middle is a lot easier]

This was the first time I've used information from a prompt box to change the SVG elements, and I think it works really well. However, the input method isn't ideal - maybe mouse clicks would be better, perhaps for some sort of game. This was also the first time I've used the createElementNS function to add new elements (the bars) to the SVG, which is a useful method to know. I think, for this project, it might have been more efficient to clone one of the bars. I also had to learn a bit about manipulating parent and child nodes, particularly, to clear graph if new data is added, which is also a handy thing to be able to do. Now I should be able to manipulate just about every aspect of the SVG.


I spent a bit more time playing with my graph builder, fixing bugs and trying out new techniques. This version (below) draws line graphs, and can display multiple series. I'm particularly pleased with how it rescales the data when necessary. I also added some tooltips, since I'd worked out how to make them. Next, I'd like to add a way to remove series, and to display values on the axes. It would also be good to be able to see values by mouse-overing the lines.

// *** To do *** // Add axis values // Ability to remove series // Show point values on mouseover X-axis label Y-axis label Add Series Tooltip

The code for these SVGs is on here.