2017-06-04 112 views
1

我正在尋找一個解決方案,當我使用減少添加/刪除功能時,我可以刪除空箱。刪除空箱與減少添加刪除功能不工作

我有一個的jsfiddle here

空箱被刪除時,我想提供「點」的簡單相加,而不是當我想用一個平均計算,並在圖中使用的valueAccessor。

我的數據被設置如下:

{Season:"2016/17", 
Manager:"Alan Curtis", 
Points:1, 
Formation:"4231", 
date:"01 February 2017"}, 

{Season:"2016/17", 
Manager:"Paul Clement", 
Points:1, 
Formation:"442", 
date:"01 February 2018"}, 

{Season:"2015/16", 
Manager:"Paul Clement", 
Points:3, 
Formation:"433", 
date:"01 May 2017"}, 

而我的目標是提供一個「點每場比賽的平均,由「經理」,也可以通過「組」。

我使用了減少添加/刪除功能:

function reduceAdd(p, v) { 
    p.total += v.Points; 
    ++p.count; 
    p.ppg = d3.round((p.total/p.count), 2); 
    return p; 
    } 

function reduceRemove(p, v) { 
    p.total -= v.Points; 
    --p.count; 
    p.ppg = d3.round((p.total/p.count), 2); 
    return p; 
    } 

function reduceInitial() { 
    return { 
     total: 0, 
     count: 0, 
     ppg: 0, 
     }; 
    } 

和刪除空箱碼:

function remove_empty_bins(source_group) { 
return { 
    all:function() { 
     return source_group.all().filter(function(d) { 
      return d.value !=0; 
     }); 
    } 
}; 
} 

我的圖表代碼:

managerChart 
    .dimension(dimManager) 
    .group(ManagerPPGGroup) 
    .ordering(function(p) { return -p.value.ppg }) 
    .renderLabel(false) 
    .othersGrouper(null) 
    .renderTitle(false) 
    .renderTitleLabel(true) 
    .margins({top: 10, left: 10, right: 20, bottom: 80}) 
    .valueAccessor(function(p) 
     { if (p.value.ppg >0) { 
     return p.value.ppg } else { return "n/a"}; }); 

formationChart 
    .dimension(dimFormation) 
    .group(filteredFormationPPGGroup) 
    .ordering(function(p) { return -p.value.ppg }) 
    .renderLabel(false) 
    .cap(10) 
    .elasticX(true) 
    .renderTitle(false) 
    .renderTitleLabel(true) 
    .margins({top: 10, left: 10, right: 20, bottom: 80}) 
    .valueAccessor(function(p) { return p.value.count > 0 ? p.value.ppg : "not used"; }); 

一切正常,除了應用過濾器時不會清空空箱。

我嘗試了各種各樣的事情來嘗試解決問題,更改圖表的valueAccessor和remove_empty_bins函數,但似乎沒有任何工作。

我目前的解決方法是在圖表上提供「未使用」文本,以便用戶知道管理器未使用該陣列,但我更願意按預期移除空箱。

在此先感謝您的幫助。

+1

直接與問題無關,但您應該在dc中執行'd3.round((p.total/p.count),2)'計算。js'valueAccessor',而不是在Crossfilter組中。只需使用該組來跟蹤「總計」和「計數」。爲什麼?假設您有1000條記錄,並篩選出500條記錄。這個計算在那個過程中會運行500次,當你只需要運行一次,當你顯示平均值時。 –

+0

感謝您的提示,很高興知道。我會做出改變 – Kevin

回答

2

是的,remove_empty_bins需要調整,如果減少產生一個對象,而不是一個數字。

我想不出任何一般的方式來做到這一點,不會使效率低下,*讓我們調節功能,這種用例:

function remove_empty_bins(source_group) { 
    return { 
     all:function() { 
      return source_group.all().filter(function(d) { 
       return d.value.total != 0; 
      }); 
     } 
    }; 
} 

我們只需要拉.total出於對象,因爲an object (almost) never equals zero

作爲獎勵,我還設置了酒吧一個固定的高度在你的提琴:

formationChart 
    .fixedBarHeight(30) 

否則,當有一個酒吧,它會成長,以適應整個區域,許多人考慮醜陋。

我也應用過濾到經理rowChart。你的小提琴叉:https://jsfiddle.net/gordonwoodhull/qw0oe8ea/6/

*也許是時候了謂詞來重構爲remove_bins()呢?但是,在沒有箭頭功能的瀏覽器消失之前,這並不簡單。

+0

再次感謝戈登,非常感激。我嘗試了各種不同的東西,刪除空箱功能,但沒有任何我試過! – Kevin