我在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
我想控制所生成密钥中各项的顺序。 (颜色不太重要。)
答案 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"))
这将使基础数据和颜色分配保持不变。
编辑:要更改列堆栈的顺序,可以在绘制类之前为其分配因子级别。请注意,如果采用此选项,则无需为图例再次手动指定中断,因为它们默认情况下会遵循因子水平。
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代码。如果您对解决方案感到满意,请将其标记为正确答案。谢谢:)