[Chartjs]-Is there a convenient way to print values to a JS chart from a CSV file without converting it?

2👍

There is a Chart.js plugin chartjs-plugin-datasource that makes it easy to load data from CSV files. By default, each row in a CSV file will be mapped to one dataset, and the first column and the first row will be treated as dataset labels and index labels respectively. You can also customize how to parse CSV data using options.

<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datasource@0.1.0"> </script>

<canvas id="myChart"></canvas>
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
    type: 'bar',
    plugins: [ChartDataSource],
    options: {
        daatasource: {
            url: 'phone-market-share.csv'
        }
    }
});

1👍

I mean, if you’ve got the csv string, let’s assume that the variable is csv

OS,2009,2010,2011,2012,2013,2014,2015,2016,2017
Android,1.6,9.6,36.4,56.9,74.4,80.8,78.8,84.1,86.1
iOS,10.5,15.4,16.9,22.5,18.2,15.3,17.9,14.8,13.7
Microsoft,10.2,6.8,2.6,1.9,2.9,2.7,2.5,0.7,0.1
RIM,20.6,19.7,13,6.8,3,0.6,0.4,0.2,0
Symbian,48.8,44.2,27.7,8.5,0.6,0.2,0.1,0,0

first split it by newlines and then split it by commas like so.

const array = csv.split('\n').map(col => col.split(','));

Leave a comment