2017-02-03 90 views
1

我想ggplot(R)基於計算表中的多個數字列與某個分類列的計算聚合值的條形圖(這也是「group by」 )的表。使用多列的R/ggplot2聚合函數

表:

V1 V2 categorical 3 4 c1 5 6 c2 7 3 c2 3 8 c3

我願做這樣的事情:

ggplot(Table, aes(categorical)) + stat_summary_bin(aes="V1 * V2"), fun.y = function(r) r$V1 * r$V2)

其中塞到fun.y函數接受一個行,然後訪問其對應的V1和V2值返回將映射到y軸的內容。 期望的結果將是3條曲線其中c1:12,C2:51,和C3:24

+0

的後續問題是[這裏](HTTP: //stackoverflow.com/q/42036505/2019874) – juanchito

回答

2

只要你只是想從每一行添加的結果,geom_barposition = "stack"會做得很好。 aes()是非常自由的,你可以通過列的功能傳遞給它。

ggplot(df, aes(x = categorical, y = V1 * V2)) + 
    geom_bar(stat = "identity", position = "stack") 

enter image description here

2

或者與stat_summary_bin工作,你可以指定fun.y參數爲sum

ggplot(df, aes(x = categorical)) + 
    stat_summary_bin(aes(y = V1 * V2), fun.y = "sum", geom = "bar") 

enter image description here