在D3

2016-08-25 67 views
0

與局部平均數據比較元件I具有以下數據在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 }] 

它需要將​​與​​組平均值對每個dayofweek比較。 即對於第一行,devcoun t = 1將與用於dayofweek-0(= 1.5)的平均設備計數進行比較,並且如果​​較小則將返回「是」。否則應退回「否」。

我編碼如下。

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中用於創建矩形並在比較後需要用於確定矩形顏色的輸出

+2

這表明你已經試過這麼胖(用'map','filter','d3.mean'或其他任何東西)是個好主意。否則,你似乎希望人們免費爲你編寫代碼。在那種情況下,我出去了。 –

+1

暗示我會建議你看看d3.nest和d3.mean應該幫助你。 – Cyril

+0

謝謝赫拉爾多和西里爾。我不知道如何繼續這個。我不是d3的專家。我嘗試過使用d3.nest(),但無法將結果數據與此數據結合起來 –

回答

1

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

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>