this question的答案对我也非常有帮助。我只需要提示一件事:
如果我在一组具有不同y值的区域上重复绘图,我如何摆脱y-scale-Labels中的符号?
到目前为止,这是我的代码:
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))
这对我来说非常适合,即使在通过各区的循环中也是如此。
非常感谢!
答案 0 :(得分:2)
由于您正在执行coord_flip
,因此您必须更改y轴值的标签(在翻转时变为x轴)。
添加以下行,但不是(-5到+5)将它们设置为geom_bars可以的最大+ ve和-ve值,具体取决于数据。我们只是将轴值标签设置为断点的绝对值。
+ scale_y_discrete(breaks=seq(-5,5,by=1),labels=abs(seq(-5,5,by=1)))
我没有您的完整数据,但添加上面的行会处理减号并产生:
看起来哈德利已经想到了这一点。如果不指定中断,只需将值设为绝对数字,以便不打印负值。尝试添加:
+ scale_y_discrete(labels=abs)