Positioning values of stacked barchart in the center using ggplot2 [duplicate]

巧了我就是萌 提交于 2019-12-02 14:32:43

问题


I've created a stacked barchart and faceted using two variables. I'm unable to position the values in the barchart in the middle, it either appears at the extremes or overlaps. The expected image is the following:

I've pasted the script below. Any help would be appreciated.

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)

回答1:


You no longer need to calculate the position variable. Starting in ggplot2_2.2.0, text can be stacked and centered via position_stack.

The relevant line of geom_text code is below. Notice I don't need to use the "pos" variable at all for text placement.

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

The code for the plot and the resulting graph:

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() 



来源:https://stackoverflow.com/questions/40684549/positioning-values-of-stacked-barchart-in-the-center-using-ggplot2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!