4

I have a column ("category") that is factored with a specific order (it should spell "order" in the legend).

For the plot, I'm using a different subset of the data for each layer. When merging the data back together for the legend the factor's order changes.

Any ideas on how to prevent this reordering?

library(ggplot2)
library(dplyr)
library(tidyr)

# make some data
set.seed(12345)
count = 5
data = data.frame(
  location = LETTERS[1:count],
  o=runif(count), r=runif(count), d=runif(count), e=runif(count), R=runif(count)
)
data = data %>%
  arrange(o) %>%
  mutate(rank = 1:count) %>%
  gather('category', 'value', o:R)

# arrange the factor for category
# NOTICE THE ORDER HERE
data$category = factor(data$category, levels=c('o', 'r', 'd', 'e', 'R'))

# get subsets
subsetO = data %>% filter(category=='o')
subsetNotO = data %>% filter(category!='o')

# confirm that the subset has the same factor levels as the original
all(levels(subsetO$category) == levels(data$category))

ggplot(data = data, aes(x=location, fill=category)) +
  geom_bar(data = subsetO, aes(y=value), stat='identity', position='stack') +
  geom_bar(data = subsetNotO, aes(y=-value), stat='identity', position='stack')

enter image description here

Edit: I have in already re-factored the column (which is the solution in many of the supposed duplicates)

sharoz
  • 6,157
  • 7
  • 31
  • 57
  • possible duplicate of [Controlling ggplot2 legend display order](http://stackoverflow.com/questions/11393123/controlling-ggplot2-legend-display-order) – drmariod Aug 18 '15 at 06:01
  • Both suggested duplicates appear to fail to reorder the factor or the data. That is not the issue here. – sharoz Aug 18 '15 at 06:08

1 Answers1

4

To also provide an answer to your question, you can order the colours individually with a scale_fill_discrete.

ggplot(data = data, aes(x=location, fill=category)) +
  geom_bar(data = subsetO, aes(y=value), stat='identity', position='stack') +
  geom_bar(data = subsetNotO, aes(y=-value), stat='identity', position='stack') + 
  scale_fill_discrete(breaks = data$category)

A lot of these kind of questions can be answered by reading the following website Cookbook for R - Graphs

drmariod
  • 11,106
  • 16
  • 64
  • 110