2014-09-12 4 views
1

일부 일반 데이터가있는 경우. 내가 시도하고 사용하는 경우 geom_text(... aes(label = paste(round(..count../sum(..count..)*100),"%"))facet_grid 내의 백분율 레이블 인쇄

나는 각 격자 요소 내의 각 z 비율을 (AE, 수, AF 등) 인쇄 걸려

dx <- data.frame(x = c(sample(letters[1:4], 1000, replace=TRUE)), 
       y = c(sample(letters[5:7], 1000, replace=TRUE)), 
       z = c(sample(1:10, 5000, replace=TRUE))) 

dx$z <- as.factor(dx$z) 

d <- ggplot(dx, aes(z, fill=z)) + 
    geom_bar() + 
    facet_grid(y~x) 

d 

..

나는 같은 비율을 얻을 총 Z의 기능

내가 읽은 것에서 플로팅하기 전에 백분율을 계산하는 것이 더 쉽습니다.

question에서 사용 된 나는, ddply 기능을 사용하여 시도

,
을하지만 내 데이터의 길이를 변경합니다. 다음

d <- ggplot(dx, 
       aes(z, fill =z)) + 
    geom_bar() + 
    facet_grid(y ~ x)+ 
    geom_text(position = "identity", aes(label = paste(round(m$pct), "%")), 
      color = "black", y = 40) + 
    scale_x_discrete(drop=F) 

음모를 시도

m = ddply(data.frame(table(df)), .(x, y), mutate, pct = round(Freq/sum(Freq) * 100, 1)) 

나에게 오류

Error: Aesthetics must either be length one, or the same length as the dataProblems:paste(round(m$pct), "%") 

을주는 경우 어떤 도움을 크게 그것은 geom_text 내 명령이나 ddply

+2

사용할 수있는 경우'(난 당신이 측면의 많은 및 z의 수준이 특히,이 단지 N (%)을 보여주기 위해 많은 양의 잉크를 생각 할) dplyr'을 사용하면 그룹화 된'z' 퍼센트를 얻을 수 있습니다 :'dx %> % group_by (x, y) %> % summarize (pct = n()/sum (z))' – hrbrmstr

답변

2

당신이 링크 된 질문에서 리드를 복용에 그리드까지에 걸쳐 비율을 추가 미학과.

enter image description here

library(ggplot2) 
library(plyr) 

# Reduced the dataset 
set.seed(1) 
dx <- data.frame(x = sample(letters[1:2], 1000, replace=TRUE), 
       y = sample(letters[5:6], 1000, replace=TRUE), 
       z = factor(sample(1:3, 5000, replace=TRUE))) 

# Your ddply call 
m <- ddply(data.frame(table(dx)), .(x,y), mutate, 
            pct = round(Freq/sum(Freq) * 100, 0)) 

# Plot - with a little extra y-axis space for the label  
d <- ggplot(dx, aes(z, fill=z)) + 
       geom_bar() + 
       scale_y_continuous(limits=c(0, 1.1*max(m$Freq))) + 
       facet_grid(y~x) 


d + geom_text(data=m, aes(x=z, y=Inf, label = paste0(pct, "%")), 
                vjust = 1.5, size = 5) 

1

를 사용하는지 여부, 감사합니다 당신이 의미하는 z의 몫이 아니라 또한 함께 geom_text 호출에 ddply에 의해 반환 된 새로운 dataframe을 통과해야

을 : 1.

require(plyr) 
helper<-sum(dx$z) 
datac <- ddply(dx, c("x","y"), summarise, zshare=sum(z)/helper) 

dx$z <- as.factor(dx$z) 

d <- ggplot(data=dx) 
d <- d + geom_bar(aes(z, fill=z)) 
d <- d+ facet_grid(y~x) + geom_text(data=datac,aes(x=3,y=60,label=paste(round(zshare,3)*100,"%"))) 
d 

enter image description here

+0

감사합니다. 각 그리드마다 각 z 값 (1:10)의 (ae, be, ce, de, af ...) 각 격자 내에서 백분율의 합은 100이어야합니다. – lukeg