Creating Charts from CSV

With CanvasJS, we can easily create charts from CSV. Comma Separated Value (CSV) stores the tabular data in plain-text format with a separator between each column and new line between every row.

We will be using following CSV format in this example:

5,9
6,9
7,14
8,12
9,14
10,18
11,13
12,8
13,11
14,13

Here is the code for creating Charts from CSV. We will get CSV Data using AJAX call (jQuery) and convert the same to CanvasJS supported format (Please refer to Working with Data). Then we will initialize a chart and pass the data to be rendered.

var dataPoints = [];

function getDataPointsFromCSV(csv) {
    var dataPoints = csvLines = points = [];
    csvLines = csv.split(/[\r?\n|\r|\n]+/);
        
    for (var i = 0; i < csvLines.length; i++)
        if (csvLines[i].length > 0) {
            points = csvLines[i].split(",");
            dataPoints.push({ 
                x: parseFloat(points[0]), 
                y: parseFloat(points[1]) 		
	    });
	}
    return dataPoints;
}
	 
$.get("https://canvasjs.com/services/data/datapoints.php?xstart=5&ystart=10&length=10&type=csv", function(data) {
    var chart = new CanvasJS.Chart("chartContainer", {
        title: {
	    text: "Chart from CSV",
        },
        data: [{
	    type: "line",
	    dataPoints: getDataPointsFromCSV(data)
	}]
    });
		
    chart.render();

});

Finalising

To summarize, in order to create a charts from CSV, we just need to parse the data to CanvasJS supported format and then pass the dataPoints to the chart.

Below is the compilation of final code.

Try Editing The Code

If you have any questions, please feel free to ask in our forums.Ask Question