数据框中列的总和的条形图

时间:2017-08-26 18:31:47

标签: r dataframe ggplot2 bar-chart cptbarplot

我有一个包含190个观察(行)的数据框。有五列,其中每个条目的值为0或1 如何获得一个条形图,其中x-Axis上有五列的名称,每列的数字为1(即总和)作为条形的高度 - 最好是ggplot?
对不起,我没有任何样本数据,我无法弄清楚如何生成符合描述的较小数据框。

2 个答案:

答案 0 :(得分:4)

只需获取列总和并制作一个条形图。

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

https://serverfault.com/a/56923/94862

答案 1 :(得分:3)

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