Barplot from Sums of Columns in Data Frame

10,754

Solution 1

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

Solution 2

Just take the column sums and make a barplot.

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

Barplot

Share:
10,754
Lukas
Author by

Lukas

Updated on June 05, 2022

Comments

  • Lukas
    Lukas almost 2 years

    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.

  • 5th
    5th over 6 years
    If you want to use r more often you should learn how to use apply or lapply