Generating graph from an HTML Txt

Asked

Viewed 1,742 times

1

How do I take data from a txt file and play in html to generate a graph??

I’m using that Highcharts tool, and I’d like to know how to play the values on the date, so I can generate the chart.

series: [{
    name: 'Sensor 1',
    data: [12 , 15 ,30, 10,]
}]

grateful in advance.

1 answer

0


You can create your file as a .csv (comma-separated values), similar to this:

0,1,3,7,10,10,9,7,7,6
5,4,3,3,4,4,5,6,7,10
8,8,7,8,7,7,6,4,3,2

Separate it into lines using . split:

linhas = texto.split(/\r\n|\n/);

And then by commas:

prov = linhas[j].split(',');

Then we create a "graphic" object, whose property .series.data is the information on your chart itself:

grafico.series[j] = [];
grafico.series[j].data = prov; // atribuindo o gráfico lido acima

And finally we created our Chart:

Highcharts.chart('container', grafico);

The result:

gráfico renderizado

Test the example below!
(Create a file separated by commas and lines as shown above to test)

document.getElementById('arquivo').addEventListener('change', abrirArquivo, false);

var leitor = new FileReader();
var linhas;
var grafico = [];
var prov = [];
grafico.series = [];

function abrirArquivo(a) {
  var arquivo = a.target.files[0];
  if (!arquivo) {
    return;
  }
  leitor.readAsText(arquivo);
  
  }
  
  leitor.onload = function(e) {
    var conteudo = e.target.result;
    lerDados(conteudo);
  };

function lerDados(texto) {
    linhas = texto.split(/\r\n|\n/);

    for (var j = 0; j < linhas.length; j++) {
        prov = linhas[j].split(',');
        for(var i=0; i<prov.length; i++) {
            prov[i] = parseInt(prov[i], 10);
        }

        grafico.series[j] = [];
        grafico.series[j].data = prov;
        // grafico.series[j].name = "test";
    }
    Highcharts.chart('container', grafico);
}
#container {
	min-width: 400px;
	max-width: 400px;
	height: 270px;
	margin: 0 auto
}
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<div id="container"></div>
<input type="file" id="arquivo"/>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.