2012-07-19 3 views
10

해당 양동이에 떨어지는 관측치의 백분율로 막대 차트에 의 부분에면에 주석을 추가하려고합니다. 이 질문은이 질문과 매우 밀접하게 관련되어 있습니다. Show % instead of counts in charts of categorical variables하지만 패싯 도입으로 주름이 생깁니다. 관련 질문에 대한 답변은 텍스트 기하 구조 승/stat_bin을 사용하는 것입니다 다음 라벨은 그렇게 같이 구성 할 수있다 : 이것은 않은 측면 플롯을 위해 잘 작동조건부 계산 .. faceting 변수에 대한 합계

stat_bin(geom="text", aes(x = bins, 
     y = ..count.., 
     label = paste(round(100*(..count../sum(..count..)),1), "%", sep="") 
     ) 

. 그러나 패싯의 경우이 합계 (.. count ..)는 패싯을 고려하지 않고 전체 관측 모음을 합산합니다. 아래 그림은 문제를 보여줍니다. 백분율은 패널 내에서 100 %가되지 않습니다. 여기

enter image description here

위의 그림에 대한 실제 코드 :

g.invite.distro <- ggplot(data = df.exp) + 
geom_bar(aes(x = invite_bins)) + 
facet_wrap(~cat1, ncol=3) + 
stat_bin(geom="text", aes(x = invite_bins, 
     y = ..count.., 
     label = paste(round(100*(..count../sum(..count..)),1), "%", sep="") 
     ), 
     vjust = -1, size = 3) + 
    theme_bw() + 
scale_y_continuous(limits = c(0, 3000)) 

업데이트 :

df <- data.frame(x = c('a', 'a', 'b','b'), f = c('c', 'd','d','d')) 
ggplot(data = df) + geom_bar(aes(x = x)) + 
stat_bin(geom = "text", aes(
     x = x, 
     y = ..count.., label = ..count../sum(..count..)), vjust = -1) + 
facet_wrap(~f) 

enter image description here

: 요청에 따라, 여기에 문제를 다시 생산하는 작은 예입니다
+1

흥미로운 질문, 당신은 응답을 얻을 가능성이있을 것입니다. –

+0

죄송합니다 - 그렇게 했어야합니다. 지금 예제가 있습니다. –

+0

나는 또한이 문제에 직면했다. ggplot이 이것을 처리하면 좋을 것이다 ... –

답변

11

Upda tegeom_barstat = identity이 필요합니다.

간혹 ggplot 호출 외의 요약을 얻는 것이 더 쉽습니다. 당신이 우리에게 오류를 재현하는 데이터를 준 경우

df <- data.frame(x = c('a', 'a', 'b','b'), f = c('c', 'd','d','d')) 

# Load packages 
library(ggplot2) 
library(plyr) 

# Obtain summary. 'Freq' is the count, 'pct' is the percent within each 'f' 
m = ddply(data.frame(table(df)), .(f), mutate, pct = round(Freq/sum(Freq) * 100, 1)) 

# Plot the data using the summary data frame 
ggplot(data = m, aes(x = x, y = Freq)) + 
    geom_bar(stat = "identity", width = .7) + 
    geom_text(aes(label = paste(m$pct, "%", sep = "")), vjust = -1, size = 3) + 
    facet_wrap(~ f, ncol = 2) + theme_bw() + 
    scale_y_continuous(limits = c(0, 1.2*max(m$Freq))) 

enter image description here