我有一个 JavaScript 数组,如下所示:
const a: A = ...
const b0: B = ...
const b1: B = ...
f(a,b0,b1) // Fine
f(b0,a,b1,a) // Still fine
f(b0,b1) // works but I don't want it to work because I need f to accept at least one argument which has a type A
我希望使用 Google Charts 创建条形图。下面的代码给了我一个空图表......没有条形图。 x 值应该是标签,y 值在图表中创建条形。 我是否必须手动将数组值推送到数据表中?如果是这样,这将如何完成? 这是代码的摘录,n 是 JavaScript 数组:
[
{x: "Station a",y: -77.33333333333333},{x: "Station b",y: -19},{x: "Station c",y: 9.492537313432836},...
]
在我指定的 HTML 标题中
// 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);