The CSV connector
Written by Richard Heyes, RGraph author, on 26th July 2018Introduction
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
Example code
This is some example code that creates a
chart - 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.