Reputation: 521
I would like to ggplot(R) a bar graph of aggregated values based on the computation of multiple numeric columns of a table vs. some categorical column (this is also the "group by") of said table.
Table:
V1 V2 categorical
3 4 c1
5 6 c2
7 3 c2
3 8 c3
I would like to do something like this:
ggplot(Table, aes(categorical)) +
stat_summary_bin(aes="V1 * V2"), fun.y = function(r) r$V1 * r$V2)
where the function stuffed into fun.y
accepts a row and then accesses its corresponding V1 and V2 values to return what would be mapped to the y-axis.
The desired result would be a plot of 3 bars where c1: 12, c2: 51, and c3: 24.
Upvotes: 1
Views: 625
Reputation: 214927
Alternatively to work with stat_summary_bin
, you can specify the fun.y
parameter as sum
:
ggplot(df, aes(x = categorical)) +
stat_summary_bin(aes(y = V1 * V2), fun.y = "sum", geom = "bar")
Upvotes: 2
Reputation: 145745
As long as you just want to add the results from each row, geom_bar
with position = "stack"
will do just fine. aes()
is very liberal about what you can pass to it in terms of functions of columns.
ggplot(df, aes(x = categorical, y = V1 * V2)) +
geom_bar(stat = "identity", position = "stack")
Upvotes: 2