3

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.

Lukas
  • 424
  • 3
  • 6
  • 17

2 Answers2

7
### 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")

enter image description here

5th
  • 2,097
  • 3
  • 22
  • 41
  • If you want to use `r` more often you should learn how to use [`apply` or `lapply`](https://www.datacamp.com/community/tutorials/r-tutorial-apply-family) – 5th Aug 26 '17 at 19:14
6

Just take the column sums and make a barplot.

barplot(colSums(iris[,1:4]))

Barplot

G5W
  • 36,531
  • 10
  • 47
  • 80