1

给定以下示例数据:

df<-data.frame(cbind(cntry<- c("BE","ES","IN","GE","BE","ES","GE",NA,"IN","IN"),
gndr<- c(NA,1,2,2,2,2,1,1,1,2),
plcvcrcR<-c(0,1,NA,0,0,1,1,1,0,0),
plcpvcrR<-c(0,1,1,1,NA,0,0,0,0,0),
plccbrgR<- c(0,1,0,NA,0,1,0,1,1,0),
plcarcrR<-c(1,0,0,NA,1,0,1,0,0,0),
plcrspcR<-c(1,1,0,0,0,0,0,1,1,NA)))
colnames(df)<- c("cntry", "gndr", "plcvcrcR", "plcpvcrR", "plccbrgR", "plcarcrR", "plcrspcR")
df

我怎样才能制作条形图,例如为每个性别( )显示变量, ,gndr的百分比?最好将每个性别的条形图分组,并为不同的变量使用不同的颜色。1-valuesplcpvcrRplccbrgRplcarcrR

类似于这张图片,其中一种颜色代表问题,组代表性别(​​没有置信区间):

https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcSsAlUJsqdhxXHiY35FxFmVx3BREVji_ca24w9ub_OYEfZ3O50X5Q

我已经尝试过以下功能,我知道它包含许多缺陷:

barplot(((colSums(df[c(3:5)], na.rm=TRUE)/nrow(df[c(3:5)]))*100)~gndr)
4

1 回答 1

3

我会做这样的事情:

require(ggplot2)
require(reshape2)
require(scales)
require(plyr)

# remove NA from gndr
df <- df[!is.na(df$gndr), ]
# now get percentages
df.o <- ddply(df, .(gndr), summarise, 
              plcpvcrR = sum(plcpvcrR == 1, na.rm = T)/sum(!is.na(plcpvcrR)), 
              plccbrgR = sum(plccbrgR == 1, na.rm = T)/sum(!is.na(plccbrgR)), 
              plcrspcR = sum(plcrspcR == 1, na.rm = T)/sum(!is.na(plcrspcR)))
# melt it:
df.m <- melt(df.o, id.var = "gndr")

# plot it:
ggplot(data = df.m, aes(x=gndr)) + geom_bar(aes(weights=value, fill=variable), 
      position = "dodge") + scale_y_continuous(labels=percent)

可能有更简单/直接的方法来获得百分比。这是情节:

在此处输入图像描述

于 2013-02-27T18:31:25.813 回答