2016-12-09 13 views
1

を中心にされていない私は、次のデータでグラフを作っていますggplot2ラベル正しく

library(dplyr) 
library(forcats) 
library(ggplot2) 
library(scales) 

mydf <- tibble(type = c(rep(c(rep("TypeA", 4), rep("TypeB", 4)), 2)), 
       Ratings = rep(c("Top", "Middle", "Low", "NA"), 4), 
       Prop = c(0.62, 0.15, 0.15, 0, 0.32, 0.16, 0.47, 0, 0.38, 0.31, 0.31, 0, 0.16, 0.16, 0.63, 0.05), 
       Question = c(rep("Question1", 8), rep("Question2", 8))) 
mydf$Ratings <- factor(mydf$Ratings) %>% fct_inorder() %>% fct_rev() 

そしてここでは、私のコードは、チャートを作るためにです:

mydf %>% filter(Prop > 0) %>% ggplot(aes(x = Question, y = Prop, fill = Ratings)) + 
geom_bar(position = "fill", stat = "identity") + 
geom_text(aes(label = percent(round(Prop,2))), position = position_stack(vjust = 0.5)) + 
facet_grid(~ type) + scale_y_continuous(labels = percent) + 
guides(fill = guide_legend(reverse = TRUE)) 

それは以下のチャートを生成します。私は具体的にはposition = position_stack(vjust = 0.5)を使用して、バーの中央にラベルの中央を配置しました。明らかに、質問1のラベルは正しく表示されません。これはバグですか?私のデータを正しく設定していませんか?

enter image description here

+0

をあなたは、高さを定義する別の変数を作成する必要がありますラベルの詳細については、[here](https://www.getdatajoy.com/examples/r-plots/stacked-bar-graph)を参照してください。 – figurine

+0

[この回答](http://stackoverflow.com/a/6645506/5221626)では、これはggplot2 v2.2では必要なくなりました。 – Phil

答えて

1

あなたはgeom_barためposition="fill"を持っていますが、geom_textためposition_stack。結果として、geom_barスタックの先頭は常に100%ですが、geom_textスタックの先頭はそのスタック内の値の合計が何であっても同じです。 TypeAQuestion1TypeBQuestion1の値の合計は両方とも100%未満であるため、ラベルスタックの高さはバースタックの高さよりも低くなります。

バーの高さに合わせるラベルの高さをposition_fillに変更してgeom_textに変更してください。ただし、4つのバースタックのうち2つのスタックスタックの割合が100%にならないため、position_fill()を使用すると、各スタックで100%になるようにラベルを正規化しないと誤解を招くことになります)。

伝説のバー部分と同じ色の順序になるように、私も伝説を逆転、最後の行を削除しました:

mydf %>% filter(Prop > 0) %>% 
    ggplot(aes(x = Question, y = Prop, fill = Ratings)) + 
    geom_bar(position="fill", stat="identity") + 
    geom_text(aes(label = percent(round(Prop,2))), position=position_fill(vjust = 0.5)) + 
    facet_grid(~ type) + 
    scale_y_continuous(labels = percent) 

enter image description here

関連する問題