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()
我得到这个结果:
我注意到“类”项目按字母顺序显示。但我希望选择按如下方式订购它们:
- 特设的,所以选择确切的顺序
- 为了在数据中出现的顺序,所以在这种情况下,
One, Two, Three
- 在数据中出现的相反顺序:
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
我想控制生成的密钥中项目的顺序。(颜色不太重要。)
解决方案
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()
推荐阅读
- angular7 - 在 Angular 7 中列出 json 数据时出现错误“错误:尝试区分 '[object Object]' 时出错。只允许使用数组和可迭代对象”
- collections - 如何在activiti中修改多实例上的集合
- dotnetnuke - 使用 WebAPI 时具有 2sxc 的 DNN 引发 500 错误
- php - Composer 不需要 PHP Simple HTML DOM Parser 但函数未定义
- python - 字典中的格式化字符串
- java - 如何从 Java REST API 读取非常大的文件并将其流式传输到 UI 上的 ANGULAR?
- c# - WPF路径以某种大小消失
- google-app-engine - Google AppEngine 获取 403 禁止尝试更新 cron.yaml
- php - 使用 PHP 从字符串中提取特定数据
- php - 多个 ulpoad 文件中的数组到字符串错误