The answers to this question were very useful for me. There is only one thing that I still need about:
How can I get rid of the sign in the y-scale labels if I iterate over a graph based on a set of regions with different y values?
This is my code:
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)
}
( DISTRICTObviously, just a list with 16 districts.)
Data example ( 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
Results:
Including the help I got here, and some messing around with y-axis breaks, this is an important part of the final code (with some comments):
f <- max(table(as.numeric(HW$AGE),HW$SEX))
f <- ceiling(f/10^floor(log10(f)))*10^floor(log10(f))
l <- 10^floor(log10(f))
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))) +
coord_flip(xlim = c(0,110), ylim = c(-f, f))
This works perfect for me, even within the loop around the neighborhoods.
Thanks a lot!