简体   繁体   中英

Prevent ggplot2 legend from reordering labels

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM