Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how use data from txt file to build graph with chart.js

I try to find a way to use data from txt file into chart.js graphic. I'm not very friendly with JS so I ask some help... So, what I succeed was to build a beautifull simple graph using this code :

                <canvas id="myChart" style="width:100%;max-width:900px"></canvas>
            
            <script>
            const xValues = [50,60,70,80,90,100,110,120,130,140,150];
            const yValues = [7,8,8,9,9,9,10,11,14,14,15];

            new Chart("myChart", {
              type: "line",
              data: {
                labels: xValues,
                datasets: [{
                  fill: false,
                  lineTension: 0,
                  backgroundColor: "rgba(0,0,255,1.0)",
                  borderColor: "rgba(0,0,255,0.1)",
                  data: yValues
                }]
              },
              options: {
                legend: {display: false},
                scales: {
                  yAxes: [{ticks: {min: 6, max:16}}],
                }
              }
            });
            </script>

But now I would like to replace xValues and yValues with data from txt file. What could be the best solution ? I tries some code with " $.get('/staticFiles/xValues.txt', " but it didn't work, as I said I'm not very friendly with JS ..

If somebody could tell me if an easy tuto may exist . Thank you so much.

like image 628
wanwan Avatar asked Nov 14 '25 10:11

wanwan


1 Answers

No need for jQuery

Assuming running on an HTML server and assuming one text file called data.txt in the same folder as your HTML with the lines

50,60,70,80,90,100,110,120,130,140,150
7,8,8,9,9,9,10,11,14,14,15

you can do

document.addEventListener('DOMContentLoaded', () => {
  fetch('data.txt')
    .then(response => response.text())
    .then(text => {
      const lines = text.split('\n');
      const xValues = lines[0].split(',').map(Number);
      const yValues = lines[1].split(',').map(Number);

      new Chart("myChart", {
        type: "line",
        data: {
          labels: xValues,
          datasets: [{
            fill: false,
            lineTension: 0,
            backgroundColor: "rgba(0,0,255,1.0)",
            borderColor: "rgba(0,0,255,0.1)",
            data: yValues
          }]
        },
        options: {
          legend: {
            display: false
          },
          scales: {
            yAxes: [{
              ticks: {
                min: 6,
                max: 16
              }
            }],
          }
        }
      });
    })
    .catch(error => {
      console.error('Error fetching data', error);
    });
});
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<canvas id="myChart" style="width:100%;max-width:900px"></canvas>
like image 156
Godot Avatar answered Nov 17 '25 08:11

Godot