I am trying to create a population tree and I followed this very good post:
Simpler population pyramid in ggplot2
However, I seem to be unable to replicate it:
Sample data:
df <- structure(list( alter = c(18:23),
Geschlecht = c("männlich", "weiblich", "männlich", "weiblich", "männlich", "weiblich" ) ,
n = c(1,2,4,6,8,2) ) ,
row.names = 1:6,
class = "data.frame"
)
ggplot(data = df,
mapping = aes(x = alter, fill = Geschlecht,
y = ifelse(test = Geschlecht == "männlich",
yes = -n, no = n))) +
geom_bar(stat = "identity") +
scale_y_continuous(labels = abs, limits = max(df$n) * c(-1,1)) +
labs(y = "Anzahl") +
coord_flip()
str(df$alter)
My age & gender variable both seem fine:
num [1:148] 0 0 1 1 2 2 3 3 4 4 ...
chr [1:148] "männlich" "weiblich" "männlich" "weiblich" "männlich" "weiblich" "männlich" "weiblich" "männlich" "weiblich" "männlich" "weiblich" "männlich" "weiblich" "männlich" ...
However, the resulting plot looks like a mess how would I be able to fix this and make the plot look more like the plot in the original post?
Thanks in advance!
EDIT: My data looks like this:
> head(df)
# A tibble: 6 x 3
# Groups: alter [3]
alter Geschlecht n
<dbl> <chr> <int>
1 0 männlich 27
2 0 weiblich 26
3 1 männlich 43
4 1 weiblich 61
5 2 männlich 60
6 2 weiblich 55