gpt4 book ai didi

javascript - NVD3 javascript : add colors to points in a scatter plot

转载 作者:数据小太阳 更新时间:2023-10-29 06:12:28 26 4
gpt4 key购买 nike

我正在尝试根据一些具有 x、y 和 z 值的数据绘制散点图。

我的代码和NVD3网站上的例子是一样的, http://nvd3.org/ghpages/scatter.html ,除了我还计算了 z 值。比方说 z = x + y。我不想更改半径值,而是想通过在两种颜色之间插值来设置颜色。

所有点都显示在图表上,但我不知道如何为单个点设置颜色,只能为系列设置颜色。为简单起见,我首先尝试将点设置为静态颜色,如下所示:

[{"key":"X Plus Y","values":[{"x":0,"y":0,"z":0,"color":"#ff0000"}, ...]

但这不起作用,所以我想我需要在 javascript 中执行此操作。我查看了 scatterChart.js,但没有找到简单的方法。但我绝不是 JavaScript 专家,所以我可能很容易错过一些东西。

关于如何做到这一点有什么建议吗?我需要学习如何创建新模型文件吗?

我还想在工具提示中显示 z 值,但这将是第 2 步。

谢谢

最佳答案

我刚刚遇到了同样的问题,并找到了适合我的用例的解决方法 - 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>';
});

关于javascript - NVD3 javascript : add colors to points in a scatter plot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14720425/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com