O
O
ongrod22020-06-19 18:14:16
User interface
ongrod2, 2020-06-19 18:14:16

How to build graphs / charts from a table using ready-made JS solutions?

Excel has a lot of options for building graphs / charts from tables. An example of a simple manual on this topic is https://excelhack.ru/kak-postroit-grafik-v-excel-p...

Very interested in similar solutions for the web. So that any JS library can "feed" any HTML table, and then it will allow you to build graphs of various types using the data from this table.

It was not possible to find ready-made solutions in Google, usually there were just JS libraries that already need to provide ready-made data on two axes. And so that she herself could "read" the table and provide a choice of what we want to compare with what and how to visualize - this was not found (

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
Grimm26, 2020-07-03
@Grimm26

We take any HTML table:

<table class="table" id="dataTable" border="1">
      <thead>
      <th>имя</th>
      <th>возраст</th>
      </thead>
      <tbody>
        <tr><td>	Петя	</td><td>	13	</td></tr>
        <tr><td>	Саша	</td><td>	48	</td></tr>
        <tr><td>	Миша	</td><td>	62	</td></tr>
      </tbody>
    </table>

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

and feed the JS
function BuildChart(labels, values, chartTitle) {
  var ctx = document.getElementById("myChart").getContext('2d');
  var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
      labels: labels, // Наши метки
      datasets: [{
        label: "тест", // Название рядов
        data: values, // Значения
        backgroundColor: [ // Задаем произвольные цвета (0.2 - прозрачность)
          'rgba(255, 99, 132, 0.7)',
          'rgba(54, 162, 235, 0.7)',
          'rgba(255, 206, 86, 0.7)',
          'rgba(75, 192, 192, 0.7)'
        ],
        borderColor: [ // Добавляем произвольный цвет обводки
          'rgba(255,99,132, 1)',
          'rgba(54, 162, 235, 1)',
          'rgba(255, 206, 86, 1)',
          'rgba(75, 192, 192, 1)'
        ],
        borderWidth: 1 // Задаем ширину обводки секций
      }]
    },
    options: {
      responsive: true, // Даем Chart.js указание реагировать правильно.
      maintainAspectRatio: false, // Добавляем эту строку, чтобы избежать переключения на полноразмерный вид (высоту/ширину)
      scales: {
        yAxes: [{
          ticks: {
            beginAtZero: true,
          }
        }]
      },
      plugins: {
        datalabels: {
          anchor: 'end',    /* Возможные варианты:
                            'center' (по умолчанию): центр элемента
                            'start': нижняя граница элемента
                            'end': верхняя граница элемента
                            */
          align: 'top',
          formatter: Math.round,
          font: {
            weight: 'bold', // Жирность
            size: '20' // Размер
          }
        }
      }
    }
  });
  return myChart;
}

var table = document.getElementById('dataTable');
var json = []; // Первая строка – это заголовки
var headers =[];
for (var i = 0; i < table.rows[0].cells.length; i++) {
  headers[i] = table.rows[0].cells[i].innerHTML.toLowerCase().replace(/ /gi, '');
}

// Перебор ячеек
for (var i = 1; i < table.rows.length; i++) {
  var tableRow = table.rows[i];
  var rowData = {};
  for (var j = 0; j < tableRow.cells.length; j++) {
    rowData[headers[j]] = tableRow.cells[j].innerHTML;
  }

  json.push(rowData);
}

console.log(json);


// Добавляем JSON-значения в массив меток
var labels = json.map(function (e) {
  return e.имя; // Обязательно маленькими буквами
});
console.log(labels);

// Добавляем JSON-значения в массив значений
var values = json.map(function (e) {
  return e.возраст; // Обязательно маленькими буквами
});
console.log(values);

var chart = BuildChart(labels, values);

In the head we connect the library and in my example a plugin for a beautiful display of numbers:
Links to the library and plugin:
https://www.chartjs.org/
https://chartjs-plugin-datalabels.netlify.app/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question