Create a Chart With Chart.js Directly From a CSV File

Use Chart.js with CSV files

Creating charts for your website or web app today is easier than ever. There are a number of great Javascript charting libraries out there which provide good documentation and many examples.

However, almost all of these charts are created using both a JSON object for configuration as well as the dataset. This is fine as long as your data is stored in local JSON files or available as a JSON object from a REST API, but what if your data is stored in a CSV file?

Here’s a quick example of how to grab a CSV file and convert and pipe it for use with Chart.js.

Chart.js Setup

You’ll need to have a basic understanding of Chart.js. You can check out the getting started guide or read up on how to create a chart to get up and running in short order.

We’ll be creating a basic vertical bar chart based off of the vertical bar chart sample. If you take a look at the source for this example, you’ll note a couple of things:

Chart Data

var MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var color = Chart.helpers.color;
var barChartData = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: 'Dataset 1',
backgroundColor: color(window.chartColors.red).alpha(0.5).rgbString(),
borderColor: window.chartColors.red,
borderWidth: 1,
data: [
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor()
]
}, {
label: 'Dataset 2',
backgroundColor: color(window.chartColors.blue).alpha(0.5).rgbString(),
borderColor: window.chartColors.blue,
borderWidth: 1,
data: [
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor()
]
}]

};

This is the code which will set up the data for our chart. Each JSON object in the datasets array corresponds to one set of bars in the bar chart. Inside each of the JSON objects, you’ll see that you can change the label, background color, border color, border width and also set the data. In this example, random values are being used — this is the data that we’re going to replace with data from our CSV file.

Chart Creation

window.onload = function() {
var ctx = document.getElementById("canvas").getContext("2d");
window.myBar = new Chart(ctx, {
type: 'bar',
data: barChartData,
options: {
responsive: true,
legend: {
position: 'top',
},
title: {
display: true,
text: 'Chart.js Bar Chart'
}
}
});

};

This is the code that actually creates the chart and renders it to the canvas element in the DOM. We won’t be changing anything in this code, but you can read up on how to create a chart in the Chart.js documentation.

Build the Pipe: CSV to JSON Conversion

Now we’ll build a quick pipe to grab the CSV and convert it to JSON to be used by chart.js via API call.

  1. CSV file input

    For this example, we’ll use a CSV from a URL as our input:

    input file: https://raw.githubusercontent.com/flexiodata/data/master/phone-market-share/phone-market-share.csv
  2. Convert to JSON

    Next, we’ll simply convert the comma-delimited file to JSON:

    convert from: delimited to: json

    And, that’s all there is to it. Now we have JSON data ready to use.

Making the Flex.io API Call from charts.js

In order to allow this pipe to be referenced via an AJAX call, we’ll need to create an API key.

Now we’re ready to get the JSON data from this pipe via an AJAX call. We’ll add the following code to the Javascript where we want to create the chart (be sure to replace the placholder text with your pipe alias and the API key you created!):

$.ajax({
type: 'post',
url: 'https://www.flex.io/api/v1/pipes/[INSERT YOUR PIPE ALIAS HERE]/run?stream=0',
beforeSend: function(xhr) {
xhr.setRequestHeader('Authorization', 'Bearer [INSERT YOUR API KEY HERE]');
},
data: $('form').serialize(),
dataType: "json",
success: function (content) {

}
});

We’ll use the result of the AJAX call (with a little help from the wonderful Lodash library to format our JSON) as the data for our chart.

The Final Result

Once you’ve finish the above steps, you should have a simple bar chart that looks something like the chart below:

Chart.js Result Chart

Here’s the JsFiddle of this use case where you can see the full source code and play around with it. If you have any questions about this use case or other things you can do with Flex.io, please feel free to drop us a line.



Get Started

Want to give this a try on your own? Sign up today and give Flex.io a spin.