'Plot a Line chart using Chart.js with CSV Data
I need to plot a simple line chart using the chart.js library from CSV data, which is in the following format:
data.csv
"year","rate"
1952-53,3.00%
1953-54,3.00%
1954-55,3.50%
.......
I want year to be on the x-axis and rate to be on the y-axis. I need to do completely using chart.js. Can anyone help me in doing this?
Solution 1:[1]
Chartjs doesn't support direct CSV files. So you have to convert it to JSON-like format. What you can do is create a server side script in php/nodejs that will convert csv to json on the go. Then give that data to chartjs
$file="1_23.csv";
$csv= file_get_contents($file);
$array = array_map("str_getcsv", explode("\n", $csv));
$json = json_encode($array);
print_r($json);
Solution 2:[2]
One option could be to use csv()
from the D3.js library
Lets say you have that data in a data.csv
that looks something like this:
"year","rate"
1952-53,3.00
1953-54,3.00
1954-55,3.50
First create a function to map the CSV column data to an array:
function makeChart(sampledata) {
var sampledataLabels = sampledata.map(function(d) {
return d.year;
});
var weeksData = sampledata.map(function(d) {
return +d.rate;
});
var chart = new Chart('chart', {
type: "line",
data: {
labels: sampledataLabels,
datasets: [
{
data: weeksData
}
]
}
});
}
Then read it in via d3.csv()
d3.csv('so_chart.csv')
.then(makeChart);
I got most of this code from this excellent blog post from createwithdata.com
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Gijo Varghese |
Solution 2 | Stedy |