簡體   English   中英

防止ggplot2圖例重新排序標簽

[英]Prevent ggplot2 legend from reordering labels

我有一個列(“類別”),它與特定訂單一起考慮(它應該在圖例中拼寫“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')

在此輸入圖像描述

編輯:我已經重新考慮了該列(這是許多假定的重復項中的解決方案)

要同時提供問題的答案,您可以使用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,可以回答很多這類問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM