我有一个如下所示的 JavaScript 数组:
[
{x: "Station a", y: -77.33333333333333},
{x: "Station b", y: -19},
{x: "Station c", y: 9.492537313432836},
...
]
我希望使用 Google Charts 创建条形图。下面的代码给了我一个空图表......没有条形图。x 值应该是标签,y 值在图表中创建条形。我是否必须手动将数组值推送到数据表中?如果是这样,这将如何完成?这是代码的摘录,n 是 JavaScript 数组:
// load necessary google charts libraries
google.charts.load("visualization", "1", {'packages':["corechart"]});
google.charts.load('current', {'packages':['bar']});
function plot1() {
var dataPoints = []; // temporary array
var n = []; // final array with data
var chartData = new google.visualization.DataTable();
chartData.addColumn('string', 'Station');
chartData.addColumn('number', 'Arrival');
n.forEach(function (row) {
chartData.addRow([row.x, row.y]);
});
url = // localhost url with json data
// push json data to array
function addData(data) {
for (var i = 0; i < data.length; i++) {
for (var j = 0; j < data[i].delays.length; j++) {
dataPoints.push({
x: data[i].delays[j].Station,
y: data[i].delays[j].Arrival
});
}
}
// filter "no information" values from array
values = ["no information"]
dataPoints = dataPoints.filter(item => !values.includes(item.y));
// eliminate duplicates of x and get average of the y values
const map = new Map();
dataPoints.forEach(({ x, y }) => {
const [total, count] = map.get(x) ?? [null, 0];
map.set(x, [(total ?? 0) + parseInt(y), count + 1]);
});
// final array with data in desired format
n = [...map].map(([k, v]) => ({ x: k, y: v[0] / v[1] }));
console.log(n);
}
$.getJSON(url, addData);
var options = {
width: 700,
legend: { position: 'none' },
chart: {
title: 'Verteilung der Verspätungen bei Ankunft (in Sekunden)'},
axes: {
x: {
0: { side: 'top', label: 'Stationen'} // Top x-axis.
}
},
bar: { groupWidth: "90%" }
};
var chart = new google.charts.Bar(document.getElementById('plot1'));
chart.draw(chartData, google.charts.Bar.convertOptions(options));
};
google.charts.setOnLoadCallback(plot1);
在我指定的 HTML 标头中
<script src = "http://code.jquery.com/jquery-latest.js"></script>
<script src = "https://www.gstatic.com/charts/loader.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>