Dan
Dan

Reputation: 143

ggplot: change the order of stacked bars based on the a name within the bar

ggplot(data,aes(x=ab,y=Freq/total,fill=Result))+
      geom_bar(stat="identity")+
     theme(strip.text.x = element_text(size=8, angle=0),
      strip.background = element_rect(colour="black", fill="#CCCCFF"))+
    ggtitle("H.somnus SIR %")+ylab("% SIR")+
    scale_y_continuous(labels=percent,breaks=seq(0,1,.1))+
    theme_set(theme_barplot())

Above is the code that I am using. data is a table that I have melted, but the column 'result' is in an order that is alphabetical and the str(result) is a factor with 4 levels: like A,B,C,D. What I would like to display the bars with the largest bar on the bottom and the order would be D,B,C,A

Thanks

Upvotes: 2

Views: 1191

Answers (1)

OliE
OliE

Reputation: 716

It's a bit of a hacked fix but it works. ggplot will plot the stacked bars in the order it encounters them when using stat = "identity". To get the stack in the order D,B,C,A reorder your data.frame like this:

data <- data[c(data$Result == "D",
               data$Result == "B",
               data$Result == "C",
               data$Result == "A"),]

the entry in the ggplot2 help files could be better in this respect.

Upvotes: 2

Related Questions