Sharing Our Passion for Technology
& Continuous Learning
Simple SVG Graphing
Graphing is a great way to visualize a bunch of data. In this article we will talk about a simple way to make graphs for modern web browsers. We will be using dimple.js that is powered by D3. Here I will explain everything that you need to know in order to get a jump start in making SVG charts.
Preface
D3 is extremely powerful and utilizing its specificity for graphs is where dimple.js comes into play. Dimple.js lets us make graphs quickly and easily. Take a glance below at the chart we are about to create.Getting Started
We first need to pick something to graph. For this example we will pick the categories of this blogging website. If we look closely at the data, each category has a number tied to it. In other words, we now have x and y axis. We now need to put this on a website, so were going to use dimple.js and d3.js to display it correctly.Step by Step
Inside of your html, you are going to include two files, d3 and dimple.js, and create an element to hold the end result. Below is an example, in jade, so that you can understand what I am talking about: #graph
script(src="http://d3js.org/d3.v3.min.js")
script(src="http://dimplejs.org/dist/dimple.v2.1.0.min.js")
script(src=”/js/graph.js”)
As you noticed above we also included a graph.js file that we will now begin to work with.
Inside of your graph.js we will start out with making a new svg then loading the data:
var svg = dimple.newSvg("#graph", 600, 425),
data = '[{"name":"Agile","amount":"18"},............;
Above, as you can see, we are calling dimple.newSvg and passing it our container id, height and width. The height and width can be all sorts of different units, for example, a percentage. In this specific case they are in px. The second variable called data is where we will retrieve our data. For this example, we will be using pre-built data that has been pulled from the main blogs page. The full explanation of how the data has been gathered is at the end of the article.
As noted we have a dataset that is preloaded for us. This most likely is not going to be a real world for you. Typically the data would come from some type of file or service that is served by the server. This is quickly solved by relaying on d3 and pulling it in d3.tsv(‘/path.tsv’) or perhaps even d3.csv(‘/path.csv’).
Moving on to making the chart:
var chart = new dimple.chart(svg, data);
chart.setBounds(45, 5, 400, 300);
Let's explain what is above. The chart is being set to a new dimple.chart that elegantly puts our svg and data into one. We then set bounds for the chart that we just created with chart.setBounds. If you understand CSS padding, then that is basically what we are doing in the second line. Otherwise it is the bounds that the chart will be displayed in, within the #graph( 600,425 ) that we have created earlier.
Let's plot this data:
var x = chart.addCategoryAxis("x","name"),
y = chart.addMeasureAxis("y","amount"),
s = chart.addSeries(null,dimple.plot.area);
Now that we have the graph setup, we can send it some data to plot. As you remember from above, we have a json array that has two keys “name” and “amount”, so we set them up using addCategoryAxis and addMeasureAxis. To further explain, addCategoryAxis and addMeasureAxis are overloaded method of the addAxis. They basically help us write addAxis quicker and cleaner for all of the standard stuff. There are also several of them found here, for example another popular one would be addTimeAxis. Lastly we assign s to a series that we get back from the addSeries. The series can do all sorts of neat stuff, that we will not cover here, like listen for on mouseover events. We're passing in null for the first argument in order to get the series and dimple.plot.area for the second. The first argument is called a categoryField, this name can be a bit confusing but I like to think of it like a pivot. In other words. if your data had a bunch of data and we wanted to categorize or pivot the data around a specific key or keys. In this case we only have x and y in our dataset so passing null is fine here. The second argument is what type of graph should we display. This can be any of the following: area, bar, bubble, line.
Perfect! We have a chart! Let's draw it!
chart.draw(5000);
y.titleShape.text("Count");
x.titleShape.text("Categories");
We draw with a delay of 5000 to animate the data making it fun. If we left out the last two lines then our labels would be called “name” and “amount”. In order to make it clear to the user what we are displaying, changing it to “Count” and “Categories” is a big help.
Conclusion
That is it! You can now build custom svg graphs quickly and easily by harnessing the power of dimple with d3.Extras
In case you were wondering how the data was scraped for curiosity, future updates, or whatever, it was quickly done with this: var data = (function() {
"use strict";
var foo = document.querySelectorAll(".categories li.cat-item"),
output = ""
i = 0;
for(i; i < foo.length; i++ ) { if ("children" != foo[i].parentNode.className) { output += '{"name" : "' + foo[i].childNodes[0].innerText + '", "amount" : "' + foo[i].childNodes[1].textContent.replace(/[(|)]|\s/g,'') +'"},'; } };
return JSON.parse(new Array(output.slice(0,-1)));
})();
If you can’t read that, it basically gets a NodeList of .categories li.cat-item
from blogs.sourceallies.com removes any of ones that are children
of a parent class, and then cleans up the data.