我刚才遇到同样的问题,并发现适合我使用的解决方法案例 - YMMV。基本上,我的理解(来自NVD3的源代码)是,你确实只能设置一系列的颜色,而不是单个点:因此,我确实为值对象添加了一个color: '#rrggbb'
项,就像你在你的例子中做的那样只是因为我更容易构建这样的数据结构),然后设置每个系列的颜色值(我使用的是underscore.js,但您应该可以在纯JavaScript中执行此操作):
final_groups = _.map(groups, function(values, group_id) {
return { key: group_id, color: values[0].color, values: values };
});
如果您需要使用颜色连续区而不是逐点或使用离散比例来设置颜色,我使用mbostock's advice from this answer来让D3为我生成颜色值:
function compute_color_on_linear_scale(data, value, colorProperty, colorRange) {
// get a list of all the groups (this works if the colorProperty,
// aka z in your case, is numeric, otherwise the sort function
// needs to be adjusted accordingly)
// In your case, you could just write item.z rather than item[colorProperty]
// if your function doesn't need to be generic, and in that case you can
// omit the colorProperty argument from the argument list altogether
categories = _.uniq(_.map(data, function(item) {
return item[colorProperty];
}).sort(function(a,b){return a - b}), true);
// if no color range was provided, set a default one
if(typeof colorRange === 'undefined') { colorRange = ['red', 'green']; }
// this is mbostock's magic enchantment from his reply linked above
var color = d3.scale.ordinal()
.domain(categories)
.range(d3.range(categories.length).map(d3.scale.linear()
.domain([0, categories.length - 1])
.range(colorRange)
.interpolate(d3.interpolateLab)));
return color(value);
}
这应该是诀窍。我的最后一招是隐藏这个传说,因为在这种情况下这没什么意义。对于在工具提示中显示z值,您需要覆盖scatterChart()的默认tooltipContent()函数,例如,
var chart = nv.models.scatterChart()
.showDistX(true)
.showDistY(true)
.tooltipContent(function(key, x, y, obj) {
return '<h3>' + obj.point.label + ' (' + key + ')</h3>';
});
您可以自定义这个不亚于需要 - 如果你只是在函数的开头添加console.log(arguments);
,你可以在浏览器的开发工具检查到底哪个数据可供你在你的工具提示使用:
[...]
.tooltipContent(function(key, x, y, obj) {
console.log(arguments);
return '<h3>' + obj.point.label + ' (' + key + ')</h3>';
});