How do I import a csv into chart.js?

Nick picture Nick · Jan 5, 2017 · Viewed 12.8k times · Source

I have been looking for this solution but can't seem to find it . Does chart.js support this ?

I have attempted to parse in the data with papaparse, but due to my limited knowledge I can't find a solution.

Answer

nagix picture nagix · Jun 3, 2019

There is a Chart.js plugin chartjs-plugin-datasource that makes it easy to load data from CSV files.

Let's suppose you have a CSV file as shown below, and it is saved as sample-dataset.csv in the same directory as your HTML file:

,January,February,March,April,May,June,July
Temperature,7,7,10,15,20,23,26
Precipitation,8.1,14.9,41.0,31.4,42.6,57.5,36.0

Include Chart.js and chartjs-plugin-datasource in your page:

<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>

<canvas id="myChart"></canvas>

Then, specify sample-dataset.csv in your script. 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.

var ctx = document.getElementsById("myChart");
var chart = new Chart(ctx, {
    type: 'bar',
    data: {
        datasets: [{
            type: 'line',
            yAxisID: 'temperature',
            backgroundColor: 'transparent',
            borderColor: 'rgb(255, 99, 132)',
            pointBackgroundColor: 'rgb(255, 99, 132)',
            tension: 0,
            fill: false
        }, {
            yAxisID: 'precipitation',
            backgroundColor: 'rgba(54, 162, 235, 0.5)',
            borderColor: 'transparent'
        }]
    },
    plugins: [ChartDataSource],
    options: {
        scales: {
            yAxes: [{
                id: 'temperature',
                gridLines: {
                    drawOnChartArea: false
                }
            }, {
                id: 'precipitation',
                position: 'right',
                gridLines: {
                    drawOnChartArea: false
                }
            }]
        },
        plugins: {
            datasource: {
                url: 'sample-dataset.csv'
            }
        }
    }
});