Spotlight on the CSV connector
Written by Richard, on 26th July 2018Summary: This is the final spotlight article and it focuses on the AJAX based CSV connector that is bundled with RGraph. There's also an AJAX function - getCSV() - but this dedicated CSV reader is more comprehensive and more versatile.
Introduction
The CSV reader is an established (since October 2013) way of easily getting data into RGraph from CSV files.
It can be configured to a higher degree compared to the simple AJAX
function getCSV()
. This includes the ability to read from a DOM
element as well as a CSV file and it can easily handle different types
of CSV files with its getRow()
and getCol()
methods.
By using the CSV reader you can easily integrate with a database by having your database server-side script output the data in a CSV format and then use this CSV reader to fetch that file.
You may find it easier to have the script that gets the data from the database produce the page and chart, but by making an extra file whose sole job is to fetch the data and print it you could use this script on other pages or offer it as a public web service.
There's both a canvas and an SVG version of the CSV reader and those files are:
RGraph.common.csv.js
RGraph.svg.common.csv.js
The example code from the chart above
This is the code that creates the chart above - using the labelsAbove
option instead of the regular labels.
<script>
// Call the CSV import code and have it download the sample.csv
file.
// The csv argument to the callback function contains the contents of the
// CSV file.
new RGraph.CSV('/sample.csv', function (csv)
{
// Get the first column which becomes the labels
var labels = csv.getCol(0);
// Get the second column which becomes the data
var data = csv.getCol(1);
// Get the number of rows in the CSV
var numrows = csv.numrows;
// Get the number of cols in the CSV
var numcols = csv.numcols;
new RGraph.SVG.Bar({
id:'cc',
data: data,
options: {
backgroundGridVlines: false,
backgroundGridBorder: false,
title: 'A chart using the CSV reader',
titleBold: true,
titleSize: 18,
colors: ['black'],
xaxis: false,
yaxis: false,
marginTop: 35,
shadow: false,
colorsStroke: 'rgba(0,0,0,0)',
textSize: 14,
labelsAbove: true,
labelsAboveSpecific: labels,
labelsAboveOffsety: 30,
labelsAboveSize: 14,
labelsAboveColor: 'white'
}
}).wave();
});
</script>
Further reading
If you want to know more about the CSV reader or perhaps you want to use it in your project(s) then a link to the CSV reader documentation page is below. Note that despite being in the canvas section of the documentation this also applies to the SVG CSV reader.