0
votes

I'm trying to create a stacked bar plot to display for each column x1-4 how many of the total 14 observations are -1 and how many are 1. I want to get them all on the same graph - 1 bar for each column. The numbers can be treated as factors.

The data :

    x1   x2     x3    x4
1   -1    1     1      1
2   -1    1     1     -1
3   -1    1     1      1
4   -1    1     1      1
5   -1   -1    -1     -1
6    1    1     1      1
7   -1    1     1      1
8   -1    1    -1      1
9   -1    1    -1      1
10  -1    1     1      1
11  -1   -1    -1      1
12  -1    1    -1     -1
13  -1   -1    -1      1
14  -1   -1    -1     -1
1
What have you tried? Take a look at melt from the reshape2 package and it should be fairly straight forward. In general, ggplot likes things in "long" format rather than wide. - Justin
i thought of using ddply to summarize the data but i cant group it by just one column so i got stuck again ... - haki

1 Answers

2
votes

Just melt or stack your data.frame:

DF <- read.table(text="x1   x2     x3    x4
1   -1    1     1      1
2   -1    1     1     -1
3   -1    1     1      1
4   -1    1     1      1
5   -1   -1    -1     -1
6    1    1     1      1
7   -1    1     1      1
8   -1    1    -1      1
9   -1    1    -1      1
10  -1    1     1      1
11  -1   -1    -1      1
12  -1    1    -1     -1
13  -1   -1    -1      1
14  -1   -1    -1     -1",header=TRUE)

DF.stack <- stack(DF)

geom_bar uses stat_bin by default. It's not necessary to summarize yourself.

library(ggplot2)
ggplot(DF.stack,aes(x=ind,fill=factor(values))) + geom_bar()

If you want the numbers, use table(DF.stack).