2016-11-18 79 views
0

我創建了一個堆疊條形圖並使用兩個變量分面。我無法將這些值置於中間的條形圖中,它可能出現在極端或重疊的位置。預期影像如下:使用ggplot2定位堆疊條形圖的中心值

link to the image

我已經粘貼下面的腳本。任何幫助,將不勝感激。

library(dplyr) 

library(reshape2) 

library(ggplot2) 


year<-c("2000","2000","2010","2010","2000","2000","2010","2010") 

area<-c("Rural","Rural","Rural","Rural","Urban","Urban","Urban","Urban") 

sex<-c("Male","Female","Male","Female","Male","Female","Male","Female") 

city<-c(58,61,74,65,51,55,81,54)` 

village<-c(29,30,20,18,42,40,14,29) 

town<-c(13,9,6,17,7,5,5,17) 

data<-cbind.data.frame(year,area,sex,city,village,town) 

dre<-melt(data,id.vars = c("year","area","sex")) 

dre <- arrange(dre,year,area,sex,variable) %>% 
    mutate(pos = cumsum(value) - (0.5 * value)) 


a <- ggplot(dre,aes(factor(sex),value,fill=variable)) + 
    geom_bar(stat='identity',position="stack") 

b <- a + 
    facet_wrap(factor(year)~area) 

c <- b + 
geom_text(aes(label=paste0(value,"%"),y=pos), 
     position="stack",size=2,hjust=0.85,color="black") 

d <- c + 
    coord_flip() + 
    theme_bw() + 
    scale_fill_brewer() 

print(d) 

回答

3

您不再需要計算位置變量。從ggplot2_2.2.0開始,文本可以通過position_stack進行堆疊和居中。

geom_text的相關行代碼如下。注意我根本不需要使用「pos」變量來放置文本。

geom_text(aes(label=paste0(value,"%")), 
       position = position_stack(vjust = .5), size = 2, color = "black") 

的情節中的代碼和所得到的曲線圖:

ggplot(dre, aes(factor(sex), value, fill = variable)) + 
    geom_col() + 
    facet_wrap(factor(year)~area) + 
    geom_text(aes(label = paste0(value,"%")), 
       position = position_stack(vjust = .5), size = 2, color = "black") + 
    coord_flip() + 
    theme_bw() + 
    scale_fill_brewer() 

enter image description here