Javascript 带有图例和其他颜色的Google charts API散点图
我有一个例子:Javascript 带有图例和其他颜色的Google charts API散点图,javascript,google-api,google-visualization,Javascript,Google Api,Google Visualization,我有一个例子: // Load the Visualization API and the piechart package. google.load('visualization', '1.0', {'packages':['corechart']}); // Set a callback to run when the Google Visualization API is loaded. google.setOnLoadCallback(d
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart1);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart1() {
var data = new google.visualization.DataTable(
{
cols: [
{id: 'A', label: 'A', type: 'number'},
{id: 'B', label: 'B', type: 'number'},
{id: 'C', label: 'C', type:'tooltip', p:{role:'tooltip'}}
],
rows: [
{c:[{v: 2}, {v: 3}, {v:'Allen'}]},
{c:[{v: 4}, {v: 2}, {v:'Tom'}]},
{c:[{v: 1}, {v: 3}, {v:'Sim'}]}
]
})
var options = {
title: 'Age vs. Weight comparison',
hAxis: {title: 'Age', minValue: 1, maxValue: 5},
vAxis: {title: 'Weight', minValue: 1, maxValue: 5},
legend: ''
};
var chart = new google.visualization.ScatterChart(document.getElementById('chart_scatter_container'));
chart.draw(data, options);
}
当我将鼠标悬停一次数据时,工具提示将显示此数据的“我”标签。那很好
但我想看到所有的价值观不同的颜色和放置在图例中
如何操作?散点图数据表中的列是图例中显示的列,颜色不同。为了单独显示它们,您需要重新排列数据,以便每个人都有自己的列 例如,将数据表变量替换为:
var data = google.visualization.arrayToDataTable([
['x', 'Allen', 'Tom', 'Sim'],
[1, null, null, 3],
[2, 3, null, null],
[4, null, 2, null],
]);
这样做将为您提供所需的输出(我相信,检查)
然而,这种方法的问题是,在每个系列中都有大量的“null”值(因为只有一个点)。为了简化这个过程,您可以编写一个循环来遍历数据,并为新表适当地格式化数据。基本准则是:
var newTable = new google.visualization.DataTable();
newTable.addColumn('number', 'Age');
for (var i = 0; i < data.getNumberOfRows(); ++i) {
newTable.addColumn('string', data.getValue(i, 2));
newTable.addRow();
}
for (var j = 0; j < data.getNumberOfRows(); ++j) {
newTable.setValue(j, j + 1, data.getValue(j, j + 1));
}
var newTable=newgoogle.visualization.DataTable();
newTable.addColumn('number','Age');
对于(var i=0;i
(上面的代码已经过测试,但由于我无法理解的原因,不喜欢第二个for()循环)