gpt4 book ai didi

r - 你如何让 ggplot 标签同时使用标签 = abs 和标签 = 逗号?

转载 作者:行者123 更新时间:2023-12-04 01:53:46 24 4
gpt4 key购买 nike

我正在创建一个人口金字塔。我希望我的轴使用绝对值,以便我没有人口计数的负数。我还想在 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)

最佳答案

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

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

用这个代替 comma

关于r - 你如何让 ggplot 标签同时使用标签 = abs 和标签 = 逗号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37949473/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com