Dynamically creating charts of each row in an HTML table with chart.js

To achieve expected result, use below option of creating bar chart for each row using chart.js

  1. Loop table data and create array of row data
  2. Create canvas using unique id for row
  3. Loop through the data array and create chart for each row data

Note: Scale and legend must be adjusted as required for each row

code sample – https://codepen.io/nagasai/pen/XqrqRj

var table = document.querySelector('table')
var tableArr = [];
var tableLab = [];
//loop all rows and form data array
for ( var i = 1; i < table.rows.length; i++ ) {
    tableArr.push([
     table.rows[i].cells[1].innerHTML,
     table.rows[i].cells[2].innerHTML,
     table.rows[i].cells[3].innerHTML,
     table.rows[i].cells[4].innerHTML
    ]);
tableLab.push(table.rows[i].cells[0].innerHTML)
var canvas = document.createElement("canvas");
canvas.setAttribute("id", "myChart"+i);
table.rows[i].cells[5].appendChild(canvas);
}
console.log(tableArr);

//loop array of data and create chart for each row
tableArr.forEach(function(e,i){
  var chartID = "myChart"+ (i+1)
  var ctx = document.getElementById(chartID).getContext('2d');
  var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ["France", "Germany", "Italy", "UK"],
        datasets: [{
            label: tableLab[i],
            data: e,
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)'
            ],
            borderColor: [
                'rgba(255,99,132,1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:true
                }
            }]
        }
    }
});
})
table ,tr, td,th {
  border:1px solid black;
}
https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js
<table>
    <tr>
        <th>Property</th>
        <th>France</th>
        <th>Germany</th>
        <th>Italy</th>
        <th>UK</th>
        <th>Chart</th>
    </tr>
    <tr>
        <th>Coastline</th>
        <td>4,853</td>
        <td>2,389</td>
        <td>7,600</td>
        <td>12,429</td>
        <td></td>
    </tr>
    <tr>
        <th>Life Expectancy</th>
        <td>81.8</td>
        <td>80.7</td>
        <td>82.2</td>
        <td>80.7</td>
        <td></td>
    </tr>
    <tr>
        <th>Elevation</th>
        <td>375</td>
        <td>263</td>
        <td>538</td>
        <td>162</td>
        <td></td>
    </tr>
    <tr>

Leave a Comment