使用ggplot2在中心放置堆叠条形图的位置值

Vin*_*nay 0 r ggplot2 geom-bar geom-text

我创建了一个堆叠的条形图,并使用两个变量对其进行了分面。我无法将值放置在条形图的中间,它要么出现在极端位置要么重叠。预期的图像如下:

链接到图片

我在下面粘贴了脚本。任何帮助,将不胜感激。

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)
Run Code Online (Sandbox Code Playgroud)

aos*_*ith 6

您不再需要计算位置变量。从ggplot2_2.2.0开始,可以通过堆叠文本并居中position_stack

相关geom_text代码行如下。注意,我根本不需要在文本位置使用“ pos”变量。

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

绘图和结果图形的代码:

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() 
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明