将数据元素与 d3 中的部分平均值进行比较

Compare data element with partial mean in d3

我有以下数据

 [{"devcount" : 1  , "dayofweek" :0, "hour" : 1  },
  {"devcount" : 2  , "dayofweek" :0, "hour" : 2  },

  {"devcount" : 3  , "dayofweek" :1, "hour" : 2  },
  {"devcount" : 4  , "dayofweek" :1, "hour" : 3  },
  {"devcount" : 6  , "dayofweek" :1, "hour" : 4  },
  {"devcount" : 5  , "dayofweek" :1, "hour" : 5  },

  {"devcount" : 7  , "dayofweek" :2, "hour" : 5  },
  {"devcount" : 8  , "dayofweek" :2, "hour" : 6  },
  {"devcount" : 9  , "dayofweek" :2, "hour" : 7  },
  {"devcount" : 10 , "dayofweek" :2, "hour" : 9  }]

需要将devcount与每个dayofweek的组平均值devcount进行比较。 即对于第一行,devcount=1 将与 dayofweek-0 (= 1.5) 和 "yes" 的平均设备数进行比较,如果 devcount 较小。否则应返回 "No"。

我编码如下。

smry=d3.nest()
.key( function(d) { return d.dayofweek;}) 
.rollup(function(d) {return d3.mean(d, function(g) {return g.devcount; })})        
.entries(result);

我不知道如何比较smry数据和原始数据。 原始数据将在selectAll中用于创建矩形,比较后的输出需要确定矩形的颜色

您可以按照下面的代码片段所示进行操作。

 test = [{
     "devcount": 1,
     "dayofweek": 0,
     "hour": 1
   }, {
     "devcount": 2,
     "dayofweek": 0,
     "hour": 2
   },

   {
     "devcount": 3,
     "dayofweek": 1,
     "hour": 2
   }, {
     "devcount": 4,
     "dayofweek": 1,
     "hour": 3
   }, {
     "devcount": 6,
     "dayofweek": 1,
     "hour": 4
   }, {
     "devcount": 5,
     "dayofweek": 1,
     "hour": 5
   },

   {
     "devcount": 7,
     "dayofweek": 2,
     "hour": 5
   }, {
     "devcount": 8,
     "dayofweek": 2,
     "hour": 6
   }, {
     "devcount": 9,
     "dayofweek": 2,
     "hour": 7
   }, {
     "devcount": 10,
     "dayofweek": 2,
     "hour": 9
   }
 ];

 //make the summary using nest
 smry = d3.nest()
   .key(function(d) {
     return d.dayofweek;
   })
   .rollup(function(d) {
     return d3.mean(d, function(g) {
       return g.devcount;
     })
   })
   .entries(test);
test.forEach(function(t) {
    //find the value from summary for dayofweek
    var k = smry.find(function(s) {
        return (s.key == t.dayofweek)
    }); 
    //check the day of week with the mean, set the flag in the data
    if(k.values<t.devcount){
      t.flag = true;
    } else {
        t.flag = false;
    }
});

console.log(test);//this now has the flag to determine the color
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>