ggplot2:控制填充选项的顺序

时间:2018-09-04 18:16:11

标签: r 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() 

我得到这个结果:

this

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

  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

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

2 个答案:

答案 0 :(得分:0)

您可以使用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"))

plot

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

编辑:要更改列堆栈的顺序,可以在绘制类之前为其分配因子级别。请注意,如果采用此选项,则无需为图例再次手动指定中断,因为它们默认情况下会遵循因子水平。

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() 

答案 1 :(得分:-1)

假设您要订单为三,二,一,因此您需要使用:

setattr(mydata$Class,"levels",c("Three","Two","One"))

首先运行ggplot代码。如果您对解决方案感到满意,请将其标记为正确答案。谢谢:)