In part 1 we took a look at canvas vs SVG for building graphs and data visualizations. We decided that SVG would probably be better for our purposes. We can build up SVGs by hand or by using a library like jQuery after all they are simply part of the DOM. If you remember SVGs are made up of a series of simple shapes. So letâ€™s build a few little visualizations with SVG. How about a bar chart to start with? A bar chart is made up of a series of rectangles of various different heights.
First thing we need to do is include the SVG in the page. This can be done a number of ways. You can link to an .svg file, you can put it in an iframe or you can embed it directly on the page. I like embedding on the page as it saves a server trip. Now unfortunately the blogging platform Iâ€™m using doesnâ€™t support SVG, so Iâ€™ll put in raster images instead of the SVG. There are some potential security issues with SVG so that is likely the reason the platform doesnâ€™t support them. These issues will be ironed out just as security issues with HTML were ironed out years ago.
To start with we need to include an svg tag in the document and give it a few instructions
This renders a single bar of our bar chart. The code is pretty easy to understand. The rectÂ tag creates s rectangle with a width of 50 and a height of of 150 offset 20 pixels from the top left corner of the SVG. It looks like this:
Weeee! Okay so what next? Letâ€™s build up the SVG necessary for a full graph. Weâ€™re going to need a few bars as well as a legend and an axis. Letâ€™s start with a few bars
Here weâ€™ve just added a few more rectangles and reduced the height of each. Because the origin (0,0) is in the top left we also have the change the y value for each bar. This generates
Now letâ€™s add the axes. Â To do this we add a couple of lines to our SVG
Weâ€™re almost done here. Letâ€™s add some labels and a title.
Here you can see weâ€™re adding a series of X and Y axis labels as well as the title. Placing text in SVG so it looks nice in relation to the other elements is difficult. If we were programatically adding elements to the SVG we could calculate the length of the text and position it properly.Â
Now we have a full graph with a title, labels and the introduction of a kick-ass new month. Iâ€™m also comforted to know that there is always at least two monsters under the bed. It is when there is only one they get board and devour your young. True story.
All together the code looks like
In the next post weâ€™ll look at using some libraries to make our job easier.