2016-06-21 67 views
1

我正在创建一个人口金字塔。我希望我的轴使用绝对值,以便我没有负数的人口数。我还希望在x轴上用逗号格式化刻度线,以便不用30000就能读取30,000。如何让ggplot标签同时使用labels = abs和labels =逗号?

我知道labels=comma将提供使用逗号的数字,我知道labels =abs将提供绝对值的数字。 我该如何结合这两个选项?

#test data 
    mfrawcensus <- data.frame(Age = factor(rep(x = 1:90, times = 2)), 
       Sex = rep(x = c("Females", "Males"), each = 90), 
       Population = sample(x = 1:60000, size = 180)) 

censuspop <- ggplot(data=mfrawcensus,aes(x=Age,y=Population, fill=Sex)) + 
geom_bar(data= subset(mfrawcensus,Sex=="Females"), stat="identity") + 
geom_bar(data= subset(mfrawcensus,Sex=="Males"), 
     mapping=aes(y=-Population), 
     stat="identity", 
     position="identity") + 
scale_y_continuous(labels=comma) + 
xlab("Age (years)")+ ylab("Population") + 
scale_x_discrete(breaks =seq(0,90,5), drop=FALSE)+ coord_flip(ylim=c(-55000,55000)) 

我试着添加像原来的另一个比例来获得绝对值,但它没有奏效。这里是我的尝试:

censuspyramid<-censuspop+theme_bw() +theme(legend.position="none") 
    + ggtitle("a")+scale_y_continuous(labels=abs) 

回答

3

可以使一个新的函数,它的这个,而不是两个abscomma

abs_comma <- function (x, ...) { 
    format(abs(x), ..., big.mark = ",", scientific = FALSE, trim = TRUE) 
} 

使用comma