X-axis order changes in Mirrored Stacked Bar Plot
0
0
Entering edit mode
6 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?

enter image description here

ggplot2 • 617 views
ADD COMMENT
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

ADD REPLY
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

ADD REPLY
0
Entering edit mode

Tried that but didn't work.

ADD REPLY
0
Entering edit mode

Ir works on my machineenter image description here

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

ADD REPLY

Login before adding your answer.

Traffic: 1572 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

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

Powered by the version 2.3.6