X-axis order changes in Mirrored Stacked Bar Plot
0
0
Entering edit mode
11 months ago

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?

ggplot2 • 802 views
0
Entering edit mode

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

0
Entering edit mode

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 mind

0
Entering edit mode

Tried that but didn't work.

0
Entering edit mode

Ir works on my machine

The code should be added at the end of the code your provided

Traffic: 1420 users visited in the last hour
FAQ
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.