2

I have the following data.

pos <- c(1,2,3,4,5,6,1,2,3,4,5,6,1,2,3,4,5,6,1,2,3,4,5,6)
block <- c(1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2)
set <- c(1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3,4,4,4,4,4,4)
fsize <- c(4,5,6,1,2,1,2,2,3,4,5,1,7,11,2,1,2,3,5,3,5,6,1,2)

dat <- data.frame(pos,block,set,fsize)
dat <- dat[order(block,set,-fsize),]
dat$pos <- as.factor(dat$pos)

ggplot(dat, aes(x = pos, y = fsize)) + geom_bar(stat="identity") +
  facet_wrap(~block+set)

Each position pos is associated with a size fsize. There are 6 positions within each block/set. I want to arrange the sizes in decreasing female size. So for example, the first block/set with rearranged positions would be 3,2,1,5,4,6 and it would be different for the other. However, when I plot it, the x-axis gets automatically reordered to 1-6 even when I factor the pos column. Any suggestions on how to rectify this?

Rspacer
  • 2,369
  • 1
  • 14
  • 40
  • This does not help. All of the panels get ordered to `3,2,1,5,4,6` combo, whereas each panel will have its own unique arrangement of positions – Rspacer Jul 02 '18 at 17:38
  • Possible duplicate of [ggplot2: reorder bars from highest to lowest in each facet](https://stackoverflow.com/questions/43176546/ggplot2-reorder-bars-from-highest-to-lowest-in-each-facet) – Divi Jul 02 '18 at 17:55
  • Like this? `ggplot(dat, aes(x = reorder(pos, -fsize), y = fsize)) + geom_bar(stat="identity") +facet_wrap(~block+set)` But this does not solve it either – Rspacer Jul 02 '18 at 18:02
  • In that example they reorder for each plot and combine the plots together. Here I want to achieve the same thing but not have to code for each plot before combining it. – Rspacer Jul 02 '18 at 18:05

1 Answers1

3

Here is a solution, but in order to plot in the desired order, I needed to create a new variable with unique names. The variable is a combination of the set and pos columns.

dat <- data.frame(pos,block,set,fsize)

dat <- dat[order(block,set,-fsize),]
#make a key variable in the overall desired order
key<-paste(dat$set, dat$pos, sep=",")
#make an new ordered factor variable in the proper order
dat$order <- factor(key,   levels= key, ordered =TRUE)

ggplot(dat, aes(x = order, y = fsize)) + geom_bar(stat="identity") +
  facet_wrap(~block+set, scales="free_x") + labs(x="Set,Pos")

enter image description here

Dave2e
  • 22,192
  • 18
  • 42
  • 50