【问题标题】:ggplot2: Controlling the order in fill optionggplot2:控制填充选项的顺序
【发布时间】:2018-09-04 18:16:11
【问题描述】:

我在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

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

【问题讨论】:

标签: r ggplot2


【解决方案1】:

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

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

【讨论】:

  • 谢谢。这回答了我的问题。我可以提出后续问题吗?如果是这样,如果我也想更改列中数据的顺序,使数据以与键相同的顺序出现怎么办?
  • 非常感谢您抽出宝贵时间。我需要一段时间才能消化这些宝贵的答案。我点击了向上箭头,但在获得更多积分之前不会显示。 ;-)
【解决方案2】:

假设你希望顺序是三、二、一,所以你需要使用:

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

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

【讨论】:

  • 这是不正确的。这将reassign the actual levels,因此“三”现在对应于第一级,这会改变数据。
  • 我不同意你的评论!除非我弄错了,否则在他的示例中,3 不一定必须大于 1,这意味着它是分类变量而不是序数变量。
  • 如果Class不是一个因素,那是正确的,但如果Class是一个因素,“一”变成“三”。
  • @shirin 我尝试了您的代码,但得到了相同的结果。请在我的原始帖子中查看我的说明。谢谢大家。
猜你喜欢
  • 2013-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多