2013-12-15 15 views
5

facet_gridを使用して、各プロットのパーセンテージラベルが100%になる複数のプロットを作成しようとしています。R:各プロットに独立したパーセンテージラベル付きファセット棒グラフ

提供された画像では、パーセンテージラベルが49%(第1のファセット)および51%(第2のファセット)に追加されます。

私はthis Questionを見てきましたが、解決策はggplotの外にデータを集約することです。むしろそれをやりたいのですが、これはよりよいアプローチだと私は信じています。

library("ggplot2") 
library("scales") 

set.seed(123) 

df <- data.frame(x = rnorm(10000, mean = 100, sd = 50)) 

df$factor_variable <- cut(df$x, right = TRUE, 
          breaks = c(0, 25, 50, 100, 200, 10000), 
          labels = c("0 - 25", "26 - 50", "51 - 100", "101 - 200", "> 200") 
         ) 

df$second_factor_variable <- ifelse(df$x < 100, 1, 2) 

df <- sample(df, x > 0) 

table(df$second_factor_variable) 

p1 <- ggplot(df, aes(x = factor_variable, y = (..count..)/sum(..count..), ymax = 0.8)) 
p1 <- p1 + geom_bar(fill = "deepskyblue3", width=.5) 
p1 <- p1 + stat_bin(geom = "text", 
        aes(label = paste(round((..count..)/sum(..count..)*100), "%")), 
        vjust = -1, color = "grey30", size = 6) 
p1 <- p1 + xlab(NULL) + ylab(NULL) 
p1 <- p1 + scale_y_continuous(label = percent_format()) 
p1 <- p1 + xlim("0 - 25", "26 - 50", "51 - 100", "101 - 200", "> 200") 
p1 <- p1 + facet_grid(. ~ second_factor_variable) 

print(p1) 

Here is the attempt

答えて

4

作品当分の間、この方法。しかし、PANEL変数は文書化されておらず、ハドレーによれば使用されるべきではない。 データを集約してプロットするのは「正しい」方法と思われますが、これには多くの例があります。 PANEL変数が文書化されて

ggplot(df, aes(x = factor_variable, y = (..count..)/ sapply(PANEL, FUN=function(x) sum(count[PANEL == x])))) + 
       geom_bar(fill = "deepskyblue3", width=.5) + 
       stat_bin(geom = "text", 
          aes(label = paste(round((..count..)/ sapply(PANEL, FUN=function(x) sum(count[PANEL == x])) * 100), "%")), 
          vjust = -1, color = "grey30", size = 6) + 
       facet_grid(. ~ second_factor_variable) 

enter image description here

+2

? – jlhoward

+0

@jlhoward [パネル変数](http://stackoverflow.com/questions/20622332/documentation-on-internal-variables-in-ggplot-esp-panel)についてお問い合わせいただきありがとうございます。 – marbel

+1

これは興味深いアプローチですが、私の質問[ここ](http://www.stackoverflow.com/questions/20622332/)へのHadley Wickhamのコメントを参照してください。ところで、あなたの反応がどうして低下したのか分かりません。それは確かに私ではなかった。 – jlhoward

関連する問題