Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you make ggplot labels use both labels = abs and labels=comma?

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)
like image 753
Meli Avatar asked Mar 12 '23 22:03

Meli


1 Answers

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

like image 62
Richard Telford Avatar answered Apr 29 '23 13:04

Richard Telford