I'm creating a population pyramid. I would like my axis to use absolute values so that I don't have negative numbers for population count. I would also like to have the tick marks on the x-axis formatted with commas so that instead of 30000 it would read 30,000.
I know labels=comma will provide numbers that uses comma and I know that labels =abs will provide numbers that are in absolute values. 
How do I combine the two options?
  #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))
I tried adding like another scale on top of the original one to get absolute values but it didn't work. Here's my attempt:
   censuspyramid<-censuspop+theme_bw() +theme(legend.position="none")
  + ggtitle("a")+scale_y_continuous(labels=abs)
You can make a new function that does both abs and comma
abs_comma <- function (x, ...) {
  format(abs(x), ..., big.mark = ",", scientific = FALSE, trim = TRUE)
}
Use this instead of comma
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With