2012-07-19 20 views
10

私は棒グラフに、そのバケツに入っている観測のパーセンテージを内のファセットに注釈を付けることを試みています。この質問はこの質問と非常に密接に関連しています: Show % instead of counts in charts of categorical variablesしかし、ファセットの導入はしわを導入します。関連する質問への答えは、テキストGEOM/wのstat_binを使用することで、その後、ラベルがように構成されています。これは、非切子プロットのために正常に動作します条件変数ファーミング変数の合計。

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)) 

UPDATEは:

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