我有一个例子:
// 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],
]);
这样做会给你想要的输出(我相信,检查 here )。
但是,此方法的问题在于您最终会在每个系列中得到很多“空”值(因为您只有单点)。为了简化这个过程,您可以编写一个循环来遍历您的数据并为新表适本地格式化它。基本代码是:
- 将 X 值列添加到新表
- 为第 2 列(工具提示)中的每一行在新表中创建一个新列
- 对于第 1 列中的每一行(Y 值)沿对 Angular 线向下/向右填充
这看起来像这样:
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));
}
(以上代码已经过测试,但出于我无法理解的原因,不喜欢第二个 for() 循环)。
关于javascript - 带有图例和其他颜色的 Google Charts API 散点图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14381764/