首页 > 解决方案 > ggplot2:控制填充选项的顺序

问题描述

我有以下内容mydata

Class       Category
"One"       "A"
"One"       "A"
"Two"       "A"
"Two"       "A"
"Three"     "B"
"Three"     "B"
"One"       "C"
"Two"       "C"

我使用ggplot2

ggplot(mydata) +
  aes(x = Category, fill = Class) +
  geom_bar() 

我得到这个结果:

这

我注意到“类”项目按字母顺序显示。但我希望选择按如下方式订购它们:

  1. 特设的,所以选择确切的顺序
  2. 为了在数据中出现的顺序,所以在这种情况下,One, Two, Three
  3. 在数据中出现的相反顺序:Three, Two, One

答案不胜感激。

澄清

如有疑问,以下是上述数据的完整工作示例:

Class <- c("One", "One", "Two", "Two", "Three", "Three", "One", "Two", "Four")
Category <- c("A", "A", "A", "A", "B", "B", "C", "C", "C")

mydata <-  data.frame(Class, Category)

ggplot(mydata) +
  aes(x = Category, fill = Class) +
  geom_bar() 

右侧生成的 Class 键的顺序是:

Four, One, Three, Two

我想控制生成的密钥中项目的顺序。(颜色不太重要。)

标签: rggplot2

解决方案


breaks您可以使用以下参数指定图例项的顺序scale_fill_discrete()

p <- ggplot(mydata) +
  aes(x = Category, fill = Class) +
  geom_bar() 

p + scale_fill_discrete(breaks = c("One", "Two", "Three", "Four"))
p + scale_fill_discrete(breaks = c("Four", "Three", "Two", "One"))

阴谋

这使基础数据和颜色分配保持不变。

编辑:要更改列堆叠顺序,您可以在绘制之前为 Class 分配因子水平。请注意,如果您采用此选项,则无需再次为图例手动指定中断,因为它们将默认遵循因子水平。

library(dplyr)

# alternative 1: does not change the underlying data frame
ggplot(mydata %>%
         mutate(Class = factor(Class,
                               levels = c("One", "Two", "Three", "Four")))) +
  aes(x = Category, fill = Class) +
  geom_bar() 

# alternative 2: changes the underlying data frame    
mydata2 <- mydata %>%
  mutate(Class = factor(Class,
                        levels = c("One", "Two", "Three", "Four")))
ggplot(mydata2) +
  aes(x = Category, fill = Class) +
  geom_bar() 

推荐阅读