Honzo_Nebro
Honzo_Nebro

Reputation: 11

C3js, Papaparse, Parse CSV to C3js

I've been trying to parse a CSV file with Papaparse4 to use it on charts created with C3js, but I can't get it to work.

I want to be able to load different CSV files, so I'm using a file input, the file gets parsed (I can see it on the console), but I can't load the data to the chart.

You can test it here: http://jsfiddle.net/Honzo_Nebro/mv6eomf4/

function handleFileSelect(evt) {
  var file = evt.target.files[0];

  Papa.parse(file, {
    header: true,
    dynamicTyping: true,
    complete: function(results) {
      data = results;
      console.log(data);
      var chart = c3.generate({
        bindto: '#chart',
        size: {
          height: 359
        },
        json: data,
      });
    }
  });
}

$(document).ready(function() {
  $("#csv-file").change(handleFileSelect);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="csv-file" name="files" />
<div id="chart"></div>

Upvotes: 0

Views: 840

Answers (1)

Honzo_Nebro
Honzo_Nebro

Reputation: 11

So, with lots of insights from a friend we came to this. It seems to not be working on this snippet, but it does on jsfiddle, I may have misplaced something http://jsfiddle.net/Honzo_Nebro/mv6eomf4/3/

function handleFileSelect(evt) {
  var file = evt.target.files[0];

  Papa.parse(file, {
    header: true,
    dynamicTyping: true,
    complete: function(results) {
      console.log(results.data);
      //Create an empty array and fill it with the headers
      var values = [];
      $.each(results.data[0], function(key, value) {
        values.push(key);
      });
      var chart = c3.generate({
        bindto: '#chart',
        size: {
          height: 359
        },
        data: {
          json: results.data,
          keys: {
            //assign the array to the value property
            value: values,
          },
          type: 'donut',
        },
        unload: true,
        legend: {
          postion: 'bottom',
        },
        tooltip: {
          format: {
            value: function(name, ratio, id, index) {
              ratio2 = ratio * 100;
              var text = name + ", (" + ratio2.toFixed(1) + "%)";
              return name;
            }
          }
        }
      });
    }
  });
}
<script src="https://rawgit.com/mholt/PapaParse/master/papaparse.min.js"></script>
<link href="https://rawgit.com/masayuki0812/c3/master/c3.css" rel="stylesheet"/>
<script src="https://rawgit.com/masayuki0812/c3/master/c3.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="csv-file" name="files" />
<div id="chart"></div>

Upvotes: 1

Related Questions