Reputation: 543
I have a data frame with 190 observations (rows). There are five columns, in which every entry either has the value 0 or 1.
How do I get a barplot that has the name of the five columns on the x-Axis and the number of 1's (i.e. the sum) of every column as height of the bars - preferably with ggplot?
I'm sorry I don't have any sample data, I couldn't figure out how to produce a smaller dataframe that fits the descriptions.
Upvotes: 3
Views: 14313
Reputation: 2375
### Load ggplot & create sample data
library(ggplot2)
sampledata=data.frame(a=rbinom(n,1,0.7),b=rbinom(n,1,0.6),
c=rbinom(n,1,0.5),d=rbinom(n,1,0.2),e=rbinom(n,1,0.3))
### Sum the data using apply & use this for beautiful barplot
sumdata=data.frame(value=apply(sampledata,2,sum))
sumdata$key=rownames(sumdata)
ggplot(data=sumdata, aes(x=key, y=value, fill=key)) +
geom_bar(colour="black", stat="identity")
Upvotes: 8
Reputation: 37661
Just take the column sums and make a barplot.
barplot(colSums(iris[,1:4]))
Upvotes: 6