【问题标题】:How do you make ggplot labels use both labels = abs and labels=comma?如何让 ggplot 标签同时使用标签 = abs 和标签 = 逗号?
【发布时间】:2016-06-21 16:08:47
【问题描述】:

我正在创建一个人口金字塔。我希望我的轴使用绝对值,这样我就没有负数的人口计数。我还想用逗号格式化 x 轴上的刻度线,以便读取 30,000 而不是 30000。

我知道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)

【问题讨论】:

    标签: r ggplot2 axis-labels


    【解决方案1】:

    您可以创建一个同时执行abscomma 的新函数

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

    用这个代替comma

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-04
      • 1970-01-01
      • 1970-01-01
      • 2016-04-19
      • 1970-01-01
      • 2019-03-26
      • 2021-08-19
      • 1970-01-01
      相关资源
      最近更新 更多