作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想对使用 geom_bar 创建的 ggplot 的图例和图中的组进行排序。
这是一个例子
mydata <- data.frame(mygroup = c('A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'),
mysubgroup = c("north", "west", "south", "east", "north", "west", "south", "east"),
value = c(5,10,6,12, 4, 4, 3, 5))
myplot <- ggplot(mydata, aes(mygroup, value, fill = mysubgroup)) +
geom_bar(position = "dodge", width = 0.5, stat = "identity")
myplot
scale_fill_discrete(limits = c("north", "south", "east", "west"))
到情节。它按所需顺序放置图例,但不按条形排列(尽管条形已重新排列)。
myplot + scale_fill_discrete(limits = c("north", "south", "east", "west"))
mydata2 <- mydata[c(1,3,4,2,5,7,8,6),]
myplot2 <- ggplot(mydata2, aes(mygroup, value, fill = mysubgroup)) +
geom_bar(position = "dodge", width = 0.5, stat = "identity")
myplot2 + scale_fill_discrete(limits = c("north", "south", "east", "west"))
最佳答案
我在写问题时想出了答案(并将作为 CW 发布以邀请贡献)...
答案是让子组成为具有所需顺序的级别的“因素”:
mydata <- data.frame(mygroup = c('A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'),
mysubgroup = factor(c("north", "west", "south", "east",
"north", "west", "south", "east"),
levels = c("north", "south", "east", "west")),
value = c(5,10,6,12, 4, 4, 3, 5))
ggplot(mydata, aes(mygroup, value, fill = mysubgroup)) +
geom_bar(position = "dodge", width = 0.5, stat = "identity")
关于r - 如何在ggplot条形图中对子组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16528065/
我是一名优秀的程序员,十分优秀!