2017-12-04 16 views
1

サンプル・データIは、ラベルの位置を設定してみました
data <- data.frame(Country = c("Mexico","USA","Canada","Chile"), Per = c(15.5,75.3,5.2,4.0)) 

ggplot2円グラフ悪い位置

ggplot(data =data) + 
geom_bar(aes(x = "", y = Per, fill = Country), stat = "identity", width = 1) + 
coord_polar("y", start = 0) + 
theme_void()+ 
geom_text(aes(x = 1.2, y = cumsum(Per), label = Per)) 

しかし、円グラフは、実際には次のようになります。

Pie chart

答えて

1

あなたが累積和を計算する前にデータをソートする必要があります。次に、ラベルの位置を最適化することができます。 Perの半分を減算することによって:

library(tidyverse) 
data %>% 
    arrange(-Per) %>% 
    mutate(Per_cumsum=cumsum(Per)) %>% 
ggplot(aes(x=1, y=Per, fill=Country)) + 
    geom_col() + 
    geom_text(aes(x=1,y = Per_cumsum-Per/2, label=Per)) + 
    coord_polar("y", start=0) + 
    theme_void() 

enter image description here

PS:geom_colがデフォルトでstat_identityを使用しています。あるとして、それはデータを残します。

それとも単にヘルプからposition_stack

data %>% 
    ggplot(aes(x=1, y=Per, fill=Country)) + 
    geom_col() + 
    geom_text(aes(label = Per), position = position_stack(vjust = 0.5))+ 
    coord_polar(theta = "y") + 
    theme_void() 

enter image description here

を使用します。

# To place text in the middle of each bar in a stacked barplot, you 
# need to set the vjust parameter of position_stack() 
関連する問題