In this article we will take a quick walk through converting a csv file into a chart using the JS Charting jQuery plugin. Parsing csv text files is relatively simple, and visualizing the data can be even simpler.
CSV stands for comma separated values and is one of the simplest data storage formats; however, alternatives such as tab delimited files may be preferred as they better accommodate real-world data that include commas, such as street addresses.
As the name suggests, the format is made up of comma separated column values and new line separated rows. The first row of values is special, as it consists of labels identifying each column.
While there are modules to assist in parsing CSV files, we will do it directly to avoid additional overhead and get a better understanding of the process.
We start with this data in a spreadsheet and save it as a csv file.
The following code will load this CSV data and log it to the developer console.
$.get("csvArticle.csv",function(data){
console.log(data)
});
Tip: If your server does not have csv mime types, try using a .txt extension
This results in the following console output:
Dates,Mark,Gene
1/1/2015,4,12
2/1/2015,6,14
…
NOTE:There are some caveats regarding CSV and value formatting to be aware of. If the values contain commas themselves, they are surrounded by double quotes. In these cases, the tab delimited option is best.
Now, we have to parse this into strings we can use. Fortunately, this is very simple with JavaScript. First, we split the string into an array of lines using code such as data.split('\n').Then, we split each line using the same function, using a comma character, as shown in this demonstration:
Now that we understand the general idea of parsing a CSV file, let's skip some of the mundane details like quote handling, and refer to this blog post by Ben Nadel where he defines a CSVtoArray function.
Next, we will convert this array data into series and points we can visualize on a chart. Here we write a function that takes these arrays, and the column index of the x values and returns a series with points which the chart can consume.
Now we can make this CSV data come to life on our html page by using JSCharting. For a time or numeric X axis scale, it is appropriate to use a line or similar connected data point chart types. See listing of all available JavaScript chart types offered by JSCharting. Disconnected data point types like columns are more suited to category X axis values such as names.
The first step is to include jQuery and JSCharting scripts in your page.
<script src="JSC/JSCharting.js"></script>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
Shortcut: To download the JS Charting library including all samples, documentation, and supporting apps.
<div id="chart"></div>
A DIV element is required to host the chart, and chart options can be applied using the jQuery plugin syntax as shown in the following syntax:
$('#chart').JSC({ /*Chart Options*/ });
We have already converted the CSV file to a format the chart understands, so let's apply this data to a chart and set the x axis is a time scale to see what we get. The code involved in this step is:
$('#chart').JSC({
xAxisScaleType: 'time',
series: parsedData
});
So far, it looks like a solid chart. Our job could be done here, but let's see how much we can squeeze out of this simple data set.
While the chart already visualizes the data, JSCharting also has a powerful label token system that helps describe and analyze the data dynamically. So let's add a title and add as many calculations as we can into it, to promote easier analysis. The title is a chart level label which means it describes all the series in a chart. In this reference the available tokens can be found under the seriesCollection section.
titleLabelText:'2016 Sales (%sum Units)
Top Agent: %maxSeriesName, Monthly per agent: [Avg: %average, Median: %median, Mode: %mode] [Min: %min, Max: %max]'
Now lets try something cool with the axis. Consider that these units we're charting cost $125 each, and we want this chart to include this information. The y axis ticks will show the unit count, but also the dollar amount. To accomplish this we will use the following setting:
yAxisDefaultTickLabelText:'%value ({%value*125:c})'
When surrounding a token with brackets {}, it will indicate that it's an expression that should be evaluated. The expression can also be specified with a colon to include a special string to format the resulting value.
At the same time, we should include the dollar amounts in the totals, and for each agent in the legend as in this example:
Getting the data setup and visualized on a chart was easy with JSCharting. While labels can utilize callback functions, the token system makes it a lot more streamlined to decorate the chart with the information viewers need to get the most out of the data.