1

参考http://bl.ocks.org/mbostock/4061502我尝试实现从 JSON 读取数据的箱形图。从 csv 读取的代码是

d3.csv("morley.csv", function(error, csv) {
var data = [];

csv.forEach(function(x) {
var e = Math.floor(x.Expt - 1),
    r = Math.floor(x.Run - 1),
    s = Math.floor(x.Speed),
    d = data[e];
if (!d) d = data[e] = [s];
else d.push(s);
if (s > max) max = s;
if (s < min) min = s;
});

csv数据:

Expt,Run,Speed
1,1,850
1,2,740
1,3,900
1,4,1070
1,5,930
1,6,850
1,7,950
1,8,980
1,9,980
1,10,880

我将 csv 替换为 json,如下所示:

d3.json("morley.json", function(json) {
var data = json.data;
var ChartData = [];// Should Contain speed values
data.forEach(function(d,i){
  chartData.push(d.Speed);
});   
var min = d3.min(data, function(d){return d.Speed});
var max = d3.max(data, function(d){return d.Speed})

我的json是:

{
"data": [
    {
        "Expt": 1,
        "Run": 2,
        "Speed": 850
    },
    {
        "Expt": 1,
        "Run": 3,
        "Speed": 740
    },
    {
        "Expt": 1,
        "Run": 4,
        "Speed": 900
    },
    {
        "Expt": 1,
        "Run": 5,
        "Speed": 1070
    },
    {
        "Expt": 1,
        "Run": 6,
        "Speed": 930
    }]
}

当我们调用 d3.box 方法时

 var chart = d3.box()
            .whiskers(iqr(1.5))
            .width(width)
            .height(height); 

d3.box = function() {

// For each small multiple…
function box(g) {
g.each(function(d, i) {
    alert(d);
  d = d.map(value).sort(d3.ascending); // error at this line saying object dont have method map
  alert(d);
  var g = d3.select(this),
      n = d.length,
      min = d[0],
      max = d[n - 1];

当我从 csv 读取时,我没有收到错误,但是当我从 JSON 读取时,我得到这个对象没有方法映射错误。有什么区别?

4

2 回答 2

0

会是这样的

{
     "Speed": [850, 740, ...],
     "Expt": [1, 1, ...],
     "Run": [1, 2, ...]
}

如果您删除第二个参数,这是唯一json.speed有意义并返回预期结果的方法。d3.min/max

使用您的数据结构,要获得最低速度,正确的命令是

d3.min(json.data, function(d) { return d.Speed; });
于 2013-08-13T13:06:55.250 回答
0

你的问题是这样的:

    var data = json.data; 
    var ChartData = [];// Should Contain speed values
    data.forEach(function(d,i){
     chartData.push(d.Speed);
    });   
   var min = d3.min(data, function(d){return d.Speed});
   var max = d3.max(data, function(d){return d.Speed})

这对我有用:

  var jsondata = json.data;
    var chartData = [];// Should Contain speed values
    jsondata.forEach(function(d,i){
        var e = Math.floor(d.Expt - 1),
                r = Math.floor(d.Run - 1),
                s = Math.floor(d.Speed),
                d = chartData[e];
            if (!d) d = chartData[e] = [s];
            else d.push(s);
            if (s > max) max = s;
            if (s < min) min = s;
    });   

我希望我有所帮助。

于 2016-12-20T15:59:22.003 回答