2017-02-03 89 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