gpt4 book ai didi

r - ggplot : no sign on y-axis-labels 中的数字格式

转载 作者:行者123 更新时间:2023-12-01 02:19:59 24 4
gpt4 key购买 nike

this question的答案对我也非常有帮助。只有一件事我仍然需要提示:

如果我在一组具有不同 y 值的地区上迭代绘图,我如何摆脱 y 尺度标签中的符号?

到目前为止,这是我的代码:

for (district in DISTRICTS) {
HW.dist <- subset(HW,DISTRICT==district)
py <- ggplot(data=HW.dist,aes(x=as.numeric(AGE),fill=SEX))
py <- py +
geom_bar(subset=.(SEX=="F"), binwidth=1) +
geom_bar(subset=.(SEX=="M"), binwidth=1,aes(y=..count..*(-1))) +
scale_fill_grey(guide = guide_legend(title = NULL)) +
scale_x_discrete(breaks=seq(0,120,by=5),labels=abs(seq(0,120,by=5))) +
labs(y = "Count", x = "Age") +
labs(title = "Random title text") +
theme(plot.title = element_text(size = rel(1.5))) +
coord_flip()
print(py)
}

( DISTRICT 显然只是一个包含 16 个区的列表。)

示例数据 ( HW ):
SEX  AGE            DISTRICT 
M 048 Innenstadt
M 022 Innenstadt
M 029 Neustift
M 053 Neustift
F 044 Heining
F 017 Heining
F 056 Neustift
M 054 Neustift
M 030 Altstadt
M 029 Schalding
F 029 Altstadt

结果:

包括我在这里得到的帮助和对 y 轴中断的一些摆弄,这是最终代码的相关部分(有一些注释):
# How broad will the pyramid be?
f <- max(table(as.numeric(HW$AGE),HW$SEX))
# Round that up to the next power of 10 (eg 557 -> 600)
f <- ceiling(f/10^floor(log10(f)))*10^floor(log10(f))
# Use that power of 10 as breaks
l <- 10^floor(log10(f))
# f and l will be used in the 'scale_y_discrete' statement below

py <- ggplot(data=HW,aes(x=as.numeric(AGE),fill=MW))
py +
geom_bar(subset=.(SEX=="F"), binwidth=1) +
geom_bar(subset=.(SEX=="M"), binwidth=1 ,aes(y=..count..*(-1))) +
scale_fill_grey(guide = guide_legend(title = NULL)) +
scale_x_continuous(breaks=seq(0,120,by=10),labels=abs(seq(0,120,by=10))) +
scale_y_discrete(breaks=seq(-f,f,by=l),labels=abs) +
labs(y = "Count", x = "Age") +
labs(title = "Random title text") + theme(plot.title = element_text(size = rel(2))) +
# Tell ggplot not to allocate drawing space for the negative (=male) on top (flipped: right) of the positive (=female) part of the graph
coord_flip(xlim = c(0,110), ylim = c(-f, f))

这对我来说是完美的,即使在通过地区的循环中也是如此。

非常感谢!

最佳答案

既然你在做 coord_flip您必须更改 y 轴值的标签(翻转时变为 x 轴)。
添加以下行,而不是 (-5 到 +5) 将它们设置为 geom_bars 可以是的最大 +ve 和 -ve 值,具体取决于数据。我们只是将轴值标签设为中断的 abs 值。

+ scale_y_discrete(breaks=seq(-5,5,by=1),labels=abs(seq(-5,5,by=1)))     
我没有你的完整数据,但添加上面的行处理减号并产生:
enter image description here
根据 OP 的说明进行更新
看来哈德利已经想到了这一点。在不指定中断的情况下,只需将值设为绝对数字,这样它就不会打印负值。尝试添加:
+ scale_y_discrete(labels=abs)

关于r - ggplot : no sign on y-axis-labels 中的数字格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21208754/

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