Mel*_*eli 3 r ggplot2 axis-labels
我正在创建一个人口金字塔。我希望我的轴使用绝对值,以便我没有人口计数的负数。我还希望 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))
Run Code Online (Sandbox Code Playgroud)
我尝试在原始比例的基础上添加另一个比例以获得绝对值,但没有奏效。这是我的尝试:
censuspyramid<-censuspop+theme_bw() +theme(legend.position="none")
+ ggtitle("a")+scale_y_continuous(labels=abs)
Run Code Online (Sandbox Code Playgroud)
你可以做一个新的函数,它都abs
和comma
abs_comma <- function (x, ...) {
format(abs(x), ..., big.mark = ",", scientific = FALSE, trim = TRUE)
}
Run Code Online (Sandbox Code Playgroud)
用这个代替 comma
归档时间: |
|
查看次数: |
1457 次 |
最近记录: |