Reputation: 439
I have a simple code which loads the array of content and draws a pie chart.
<script type=text/javascript src=https://www.gstatic.com/charts/loader.js></script>
<script type=text/javascript>
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['Work', 11],
['Eat', 2],
['Commute', 2],
['Watch TV', 2],
['Sleep', 7]
],false);
var options = {
title: 'My Daily Activities'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
<div id="piechart" style="width: 900px; height: 500px;"></div>
I want to data table to be read from a txt file, content of the same is given below:
Task,Hours Per Day
Work,11
Eat,2
Sleep,7
Is there any way to directly load the txt file in the above code? The file might keep on changing as well.
Upvotes: 2
Views: 9636
Reputation: 61212
you can use jquery to get the text file and convert to an array.
you'll need to include two jquery files, jquery itself, and jquery csv,
along with the google charts library.
see following snippet...
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-csv/0.71/jquery.csv-0.71.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script>
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var options = {
title: 'My Daily Activities',
height: 500,
width: 900
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
// get text file
$.get('pie.txt', function(txt) {
// convert csv to an array
var arrayData = $.csv.toArrays(txt, {onParseValue: $.csv.hooks.castToScalar});
var data = google.visualization.arrayToDataTable(arrayData);
chart.draw(data, options);
});
});
</script>
<div id="piechart"></div>
Upvotes: 1