防止ggplot2图例重新排序标签

时间:2015-08-18 05:54:17

标签: r ggplot2

我有一个列(“类别”),它是一个特定订单的因素(它应该在图例中拼写“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')

enter image description here

编辑:我已经重新考虑了这个专栏(这是许多假设重复的解决方案)

1 个答案:

答案 0 :(得分:4)

要同时提供问题的答案,您可以使用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)

通过阅读以下网站Cookbook for R - Graphs

,可以回答很多这类问题