Entering edit mode
13 months ago
rohitsatyam102
▴
920
I was trying to create a mirror-stacked bar plot, but the order of the x-axis changes even when I factorize it. The test data is given here:
df_gg$age.group <- as.character(df_gg$age.group)
df_gg$age.group <- factor(df_gg$age.group,levels = c("-1","0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"))
ggplot(df_gg, aes(x=age.group, fill=group)) +
geom_bar(data = subset(df_gg, group %in% c("Non-Saudi citizens Female","Non-Saudi citizens Male","Non-Saudi citizens unknown")),
aes(y = Count), position="stack", stat="identity") +
geom_bar(data = subset(df_gg, !group %in% c("Non-Saudi citizens Female","Non-Saudi citizens Male","Non-Saudi citizens unknown")),
aes(y = -Count), position="stack", stat="identity")+scale_fill_manual(values = c("Non-Saudi citizens Female" = "red", "Non-Saudi citizens Male" = "blue", "Non-Saudi citizens unknown" = "green", "Saudi citizens Female" = "red", "Saudi citizens Male" = "blue", "Saudi citizens unknown" = "green"))
My age group is a factor and goes upto 100. Since I factorize it, the order of the age group should be 0, 10, 20 ..100. However, ggplot2 plots 0, 10, 100, 20 which is not a proper order. How can I achieve numerical order?
Maybe you could ask this on stackoverflow as this is more a programming-specific question than a bioinformatics question ? I think you would get a quicker answer there
I believe
+scale_x_discrete(limits = c("-1","0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"))
would work but there may be straightforward approaches that I do not currently have in mindTried that but didn't work.
Ir works on my machine
The code should be added at the end of the code your provided