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')
Edit: I have in already re-factored the column (which is the solution in many of the supposed duplicates)