0

I did the following stacked bar many times by specifying the factor order. Today I've tried it again. The legend respects the ordering manually defined, but the bars appear in the opposite way (from the last level to the first). For example, the legend is as follow : Factor1, Factor2, Factor3. But the first bar on the left is Factor3, then Factor2 and Factor1.

I have completely reinstalled R and RStudio, but nothing changed.

data<-read.table('file.txt', header=TRUE, sep="\t")
data$Genus<-factor(data$Genus, levels=c('Factor1','Factor2','Factor3'))   
colors<-c('color1','color2','color3')

c<- ggplot(data_gathered, aes(x=Materiel, y=Log, fill=Genus2))
    c <- c + geom_bar(stat = "identity") +
      theme_classic()+
      theme(legend.text=element_text(face="italic", size=12))+
      theme(legend.title=element_text(face="bold.italic", size=12))+
      theme(strip.background = element_blank())+
      scale_y_continuous(limits=c(0,10))+
      scale_fill_manual(values = colors)  +
      labs(y='axis title', x=element_blank(), fill='Legend') +
      coord_flip()

c

Is it a problem with my software ? What could I do?

zx8754
  • 52,746
  • 12
  • 114
  • 209
  • `data$Genus<-factor(data$Genus, levels=rev(c('Factor1','Factor2','Factor3')))`? – Axeman Feb 22 '17 at 16:34
  • The command 'rev' solved the problem of the order of the bars, but now it is the legend that is in the wrong side. –  Feb 22 '17 at 16:36
  • Then perhaps try `+ scale_x_reverse()`. – Axeman Feb 22 '17 at 16:38
  • Your example isn't reproducible, but my guess this is due to [recent changes](https://github.com/tidyverse/ggplot2/blob/master/NEWS.md#stacking) in `ggplot` where the ordering of stacked bars has changed. – Axeman Feb 22 '17 at 16:42
  • 1
    Finally, the scale_x_reverse() didn't work, but I succeded by adding guide = guide_legend(reverse = TRUE) to scale_fill_manual. Thank you very much Axeman. –  Feb 22 '17 at 16:45
  • 1
    My suggestion would be to make it an answer. I will amend the title to reflect your actual question. Hopefully this will make it more searchable. – Roman Luštrik Feb 22 '17 at 17:37
  • 1
    Similar question [here](http://stackoverflow.com/questions/42370195/change-order-of-groups-in-stacked-bar-chart-and-legend-in-r) – aosmith Feb 22 '17 at 20:57
  • Another possible duplicate: [R ggplot reverse stacked bar order](https://stackoverflow.com/q/42710056/3817004) – Uwe Aug 30 '17 at 08:32

1 Answers1

0

In order to change the order in the level, you will have to change the order of the factor in the dataset.

just try this

data$Genus<-factor(data$Genus, levels=c('Factor1','Factor2','Factor3'), ordered = TRUE)
Akshay Kadidal
  • 515
  • 1
  • 7
  • 15