Wednesday, March 29, 2017

How to draw a chart with SVG

   
    Browsers have been supporting SVG for some time now. SVG means Scalable Vector Graphics. It is an XML based vector image format. It supports animation and interactivity which means you can attach events to SVG elements just like you do for HTML elements.


    In this article, I am going to create a line chart from the following simple Json object by using Snap
Snap is the Jquery for SVG. You can select/change/add/remove Svg elements dynamically. It is an open source library by Adobe.



First, I have added the SVG tag to my HTML page. ChartStyle class has its height and width information.

First, I am going to select my SVG tag, so I can work on it. I have created another object named points to use later. This object is going to hold the data locations.

     CreateBaseLines function is responsible to create an empty chart. My charts starting point is (50,10) It's height is 190 and width is 400
chart is the SVG object we selected by Snap, we have two Snap functions here (line and text)
All we need to pass them is the coordinates of  the lines and texts. Just like Jquery, you can add attributes to the SVG elements to control their size, color, etc..


When we run this function, we end up with the following empty graph.

Now, let's try to display the data on this graph. Following function loads the data and creates points on the chart. points array is going to hold all the data locations so we can draw a line later.
 Circle is another Snap function which creates circles in SVG, just like other Snap functions you pass the coordinates to create a circle. We need to pass radius for circle too.
temp holds the Y coordinate of the data. 190 is the height of our chart so we are figuring out the Y coordinate of the data in the calculation.
50 is the margin between the months in the bottom. x1 calculates the location of months in the bottom.
0,0 coordination is the top left corner in SVG, so the number I found in temp object needs to be subtracted from the bottom of our chart to display the data in the right location.

Our chart looks like this now.

This is nice, but we can do better with one more line of code. We can connect these points to create a line chart. To do that, I am going to use another Snap function named line As you can see I am using the points object to connect my points in this function.

And here is our finalized chart.

You can see the working version in my CodePen post.


No comments:

Post a Comment