我有一列数据("category"),它是按照特定顺序因子化的(图例中应该拼写为“order”)。
对于绘图,我对每个层使用不同的数据子集。当将数据合并回图例时,因子的顺序会发生改变。
有什么办法可以防止这种重新排序的情况发生吗?
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')
编辑:我已经重新整理了该列(这是许多所谓重复问题的解决方案)