为什么域不在D3中使用d3.max(数据)? [英] Why is domain not using d3.max(data) in D3?

查看:123
本文介绍了为什么域不在D3中使用d3.max(数据)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的D3,玩弄散点图。我不能让d3.max(数据)在设置域中正常工作!

I'm new to D3 and playing around with a scatterplot. I cannot get d3.max(data) to work correctly in setting up domain!

我有以下设置一个随机数据集:

I have the following setting up a random dataset:

var data = [];
      for (i=0; i < 40; i++){
            data.push({"x": i/40, "y": i/8, "a": Math.floor(Math.random() * 3), "x2": Math.random()});
        }

然后设置我的坐标:

 var x = d3.scale.linear().domain([0, 1]).range([0 + margin, w-margin]),
            y = d3.scale.linear().domain([0, d3.max(data)]).range([0 + margin, h-margin]),
            c = d3.scale.linear().domain([0, 3]).range(["hsl(100,50%,50%)", "rgb(350, 50%, 50%)"]).interpolate(d3.interpolateHsl);

这将所有40个点放在一条水平线上。如果我将d3.max(data)替换为'5',那么它是一个对角线(虽然从左上到右下,我仍然努力翻转y坐标)。为什么d3.max(data)不能正常工作?

This puts all 40 points in a single, horizontal line. If I replace d3.max(data) with '5' then it is a diagonal (albeit from the upper left to the bottom right, I'm still struggling to flip y-coordinates). Why isn't d3.max(data) working as expected?

推荐答案

d3.max 需要一个数字数组,而不是对象。 data 的元素具有内部键值结构,并且没有办法 d3.max()知道什么取最大的。您可以使用类似 jQuery的 $。map 获取所需对象的元素,然后取最大值,例如

d3.max() expects an array of numbers, not of objects. The elements of data have an internal key-value structure and there is no way for d3.max() to know what to take the maximum of. You can use something like jQuery's $.map to get the elements of the objects you want and then take the max, e.g.

var maxy = d3.max($.map(data, function(d) { return d.y; }));

编辑:

下面的注释,你甚至不需要JQuery,因为 .map()是一个本地Array方法。代码然后变成简单的

As pointed out in the comment below, you don't even need JQuery for this, as .map() is a native Array method. The code then becomes simply

var maxy = d3.max(data.map(function(d) { return d.y; }));

甚至更简单(对于那些不实现 Array的浏览器)。使用 d3.max 的可选第二个参数告诉它如何访问数组中的值

or even simpler (and for those browsers that don't implement Array.map()), using the optional second argument of d3.max that tells it how to access values within the array

var maxy = d3.max(data, function(d) { return d.y; });

这篇关于为什么域不在D3中使用d3.max(数据)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆