[Solved] How to R present two colsums with ggplot stat_summary?


With ggplot, it is essential to have a single data frame with everything in it (at least for a single plotting layer, e.g., all the bars in a plot). You create a data frame of the column sums, and then try to use external vectors for the id and the grouping, which makes things difficult.

This is how I would do it:

means = rbind(
    data.frame(mean = colSums(M), source = "M", col = 1:ncol(M)),
    data.frame(mean = colSums(M2), source = "M2", col = 1:ncol(M2))
)

means$col = factor(means$col)
## one nice data frame with everything needed for the plot    
means
#       mean source col
# 1  -0.6400      M   1
# 2  -1.4650      M   2
# 3  -0.8850      M   3
# 4  -1.6950      M   4
# 5  -2.0300      M   5
# 6  -0.2700      M   6
# 7  -0.3640     M2   1
# 8  -1.1240     M2   2
# 9  -0.8850     M2   3
# 10 -1.2775     M2   4
# 11 -1.4770     M2   5
# 12 -0.2990     M2   6

ggplot(means, aes(x = col, y = mean, fill = source)) +
    geom_bar(stat="identity", position = 'dodge')

enter image description here

You seem to want error bars too. I have no idea what would define those error bars – if you look at geom_errorbar it expects aesthetics ymin and ymax. If you calculate whatever values you want and add them as column to the data frame above, adding the error bar to the plot should be easy.

4

solved How to R present two colsums with ggplot stat_summary?