How to use Google Chart with data from a csv

匿名 (未验证) 提交于 2019-12-03 01:05:01

问题:

I have a csv file that looks like that:

week,value1,value2 1,2,3 2,7,9 

I would like to plot a stacked graph of it using google chart (week being my x (horizontal) values and values1 and values2 being the two set of y's). Unfortunately, I didn't find any easy way to do so. That probably relates to me being a complete noob in js.

Is there any simple way to do that?

回答1:

The jquery-csv library provides the ability to translate a string of csv into an array to be used by google.visualization.arrayToDataTable() (their example here). To make this work, add jquery.csv.js to your server (in the example below I assume it is in the same folder as your HTML) and link to it in your . The following is a simple script you can add to your to get started. I assume a scatter chart, but this process works for any of the charts here. You will also need a

with id="chart" for this to work.
// load the visualization library from Google and set a listener google.load("visualization", "1", {packages:["corechart"]}); google.setOnLoadCallback(drawChart);  // this has to be a global function function drawChart() {    // grab the CSV    $.get("example.csv", function(csvString) {       // transform the CSV string into a 2-dimensional array       var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});        // this new DataTable object holds all the data       var data = new google.visualization.arrayToDataTable(arrayData);        // this view can select a subset of the data at a time       var view = new google.visualization.DataView(data);       view.setColumns([0,1]);       // set chart options      var options = {         title: "A Chart from a CSV!",         hAxis: {title: data.getColumnLabel(0), minValue: data.getColumnRange(0).min, maxValue: data.getColumnRange(0).max},         vAxis: {title: data.getColumnLabel(1), minValue: data.getColumnRange(1).min, maxValue: data.getColumnRange(1).max},         legend: 'none'      };       // create the chart object and draw it      var chart = new google.visualization.ScatterChart(document.getElementById('chart'));      chart.draw(view, options);   }); } 


回答2:

What server side scripting language are you working in (php, asp)?

One option could be to import the data from a spreadsheet saved in Google Drive, see here for a PHP based example of saving and extracting data from Google Docs. This would then enable you to update the spreadsheet and the chart would automatically plot the new data.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!