我在创造一个人口金字塔。我希望我的轴使用绝对值,这样我就不会有负数来计算人口数。我也想让x轴上的勾号用逗号来表示,这样它就不用30000来读30,000了。
我知道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)
发布于 2016-06-21 08:21:02
您可以创建一个同时执行abs
和comma
的新函数。
abs_comma <- function (x, ...) {
format(abs(x), ..., big.mark = ",", scientific = FALSE, trim = TRUE)
}
用这个代替comma
https://stackoverflow.com/questions/37949473
复制