2017-08-26 53 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