简体   繁体   English

如何使ggplot标签同时使用labels = abs和labels =逗号?

[英]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. 我还希望将x轴上的刻度线用逗号格式化,以便读取30000而不是30000。

I know labels=comma will provide numbers that uses comma and I know that labels =abs will provide numbers that are in absolute values. 我知道labels=comma将提供使用逗号的数字,并且我知道labels =abs将提供绝对值的数字。 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的新功能

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

Use this instead of comma 用它代替comma

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM