0

I am currently trying to reorder the stacks in a stacked bargraph with ggplot2 using the order argument. This works like a charm when not using facetting, but upon running facet_grid, only one of the pannels works. It is important to realize that I want to use a custom order, rather than based on size (as suggested in this topic or others concerning the use of order=desc(variable)).

You should be able to reproduce this issue using the code below

require(dplyr)
require(tidyr)
require(ggplot2)

prod<-1:8
timing<-1:4
variab<-letters[1:3]
nobserv<-length(prod)*length(timing)*length(variab)
values<-runif(nobserv)

plotset<-data.frame(product=rep(prod,each=4,length=nobserv),
                    timepoints=rep(timing,length=nobserv),
                    variable=rep(variab,each=nobserv/3),
                    values=values)

sorter<-rep(c(-2,-1,-3),each=nobserv/3)

p <- ggplot(plotset,aes(fill=variable,order=sorter,x=product,y=as.numeric(as.character(values)))) 
p <- p + geom_bar(stat='identity', position='stack')
p <- p + facet_grid(~ timepoints)
p

This will generate this graph, clearly showing only timepoint three (3) does what I want. example_graph

I do not know why this is and if and how it could be fixed. Thanks in advance for your input!

EDIT: I made a typo, now the issue should be reproducible

ps: I could reproduce the problem on both a linux and a windows machine with R 3.1.1 and ggplot2 1.0.0

Community
  • 1
  • 1
FM Kerckhof
  • 1,270
  • 1
  • 14
  • 31
  • you should be able to use `fill=factor(variable, levels=letters[1:3])`, but for some reason I'm not getting any stacking, I must have a buggy version of ggplot2. – baptiste Jan 15 '15 at 10:46
  • 1
    Your `plotset` really only has one `variable` for each `product`. So your output is impossible to reproduce. – shadow Jan 15 '15 at 10:59
  • @shadow thank you, I made a typo, now the issue should be reproducible – FM Kerckhof Jan 15 '15 at 11:04
  • @baptiste I made a minor alteration to the code: time became timing, and now I can reproduce the issue again, even with your suggested code. – FM Kerckhof Jan 15 '15 at 11:07
  • 1
    try removing `order=sorter` from aes() and it should work – baptiste Jan 15 '15 at 11:10
  • @baptiste, reordering the factor works indeed in this example, but I thinks it is very weird that the `order=sorter` argument does not work, except for timepoint 3. Is this a ggplot2 bug? Or is there something I do not understand? – FM Kerckhof Jan 15 '15 at 11:24
  • either how @baptiste, you workaround is the only good suggestion so can you maybe post it as an answer than we can close this question – FM Kerckhof Jan 19 '15 at 09:12

0 Answers0