2017-08-26 49 views
0

我有一个190个观察值(行)的数据框。有五列,其中每个条目的值都为0或1.
如何获得具有x轴上五列名称以及每个列的1(即总和)数的barplot列作为酒吧的高度 - 最好与ggplot?
对不起,我没有任何示例数据,我无法弄清楚如何生成适合描述的较小数据框。数据框中列总和的Barplot

回答

2

只需拿出列总结和做一个barplot。

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

Barplot

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

+0

如果你想使用'r'更多的时候,你应该学习如何使用['apply'或'lapply'(https://开头WWW .datacamp.com /社区/教程/ R-教程申请家庭) – 5th