0

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?

ggorlen
  • 44,755
  • 7
  • 76
  • 106
shruthi
  • 9
  • 1
  • 2

2 Answers2

0

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);
Gijo Varghese
  • 11,264
  • 22
  • 73
  • 122
  • I have converted csv to json ,but still it not happening – shruthi Dec 27 '16 at 07:04
  • also chartjs is not that good for dates. Try canvasjs http://canvasjs.com/docs/charts/basics-of-creating-html5-chart/date-time-axis/ – Gijo Varghese Dec 27 '16 at 07:07
  • I have converted csv to json ,but still it not happening below is json format: [{"FIELD1":"YEAR", "FIELD2":"RATE"},{"FIELD1":"1952-53", "FIELD2":"3.00%"},{"FIELD1":"1953-54", "FIELD2":"3.00%"}] – shruthi Dec 27 '16 at 07:10
  • Your format is not right. In the rate field. It must be integer/float. Your rate contains "%" symbol. Remove that. Also in the year field, what is "-53"? – Gijo Varghese Dec 27 '16 at 07:13
  • There's no need to go to the server for this. There are plenty of ways to do this completely in-memory in the front end. See [How to read data From *.CSV file using javascript?](https://stackoverflow.com/questions/7431268/how-to-read-data-from-csv-file-using-javascript) – ggorlen Apr 22 '22 at 03:57
0

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

Stedy
  • 7,359
  • 14
  • 57
  • 77
  • d3 seems like overkill just for CSV conversion. A dedicated CSV parsing library could do it in a fraction of the size of d3, such as [Papa Parse](https://stackoverflow.com/a/21126869/6243352). – ggorlen Apr 22 '22 at 05:35