[英]How to use Google Chart with data from a csv
我有一個看起來像這樣的 csv 文件:
week,value1,value2
1,2,3
2,7,9
我想使用谷歌圖表繪制它的堆疊圖(周是我的 x(水平)值,values1 和 values2 是兩組 y 值)。 不幸的是,我沒有找到任何簡單的方法來做到這一點。 這可能與我是一個完整的 js 菜鳥有關。
有沒有簡單的方法可以做到這一點?
jquery-csv 庫提供了將 csv 字符串轉換為google.visualization.arrayToDataTable()
使用的數組的google.visualization.arrayToDataTable()
這里是他們的示例)。 要完成這項工作,請將 jquery.csv.js 添加到您的服務器(在下面的示例中,我假設它與您的 HTML 位於同一文件夾中)並在您的<head>
鏈接到它。 以下是一個簡單的腳本,您可以將其添加到<head>
以開始使用。 我假設一個散點圖,但這個過程適用於這里的任何圖表。 您還需要一個帶有id="chart"
的<div>
才能工作。
// 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);
});
}
我已經搜索了一段時間,並在 Google 小組討論中找到了解決方案。 https://groups.google.com/forum/#!topic/google-visualization-api/cnXYDr411tQ
我試過了,它有效!
在這種情況下,我們必須指定 csv 文件的標題類型。
var queryOptions = {
csvColumns: ['number', 'number', 'number' /* Or whatever the columns in the CSV file are */],
csvHasHeader: true /* This should be false if your CSV file doesn't have a header */
}
/* csvUrl is the path to your csv */
var query = new google.visualization.Query(csvUrl, queryOptions);
query.send(handleQueryResponse);
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
var chart = new google.visualization.ColumnChart(document.getElementById('your div'));
// Draw your chart with the data table here.
// chart.draw(view, queryOptions);
}
您使用的是哪種服務器端腳本語言(php、asp)?
一種選擇是從保存在 Google 雲端硬盤中的電子表格導入數據, 請參閱此處了解從 Google Docs 保存和提取數據的基於 PHP 的示例。 這將使您能夠更新電子表格,並且圖表將自動繪制新數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.