Dav*_*415 37 graphics r ggplot2
我正在调用ggplot函数
ggplot(data,aes(x,y,fill=category)+geom_bar(stat="identity")
Run Code Online (Sandbox Code Playgroud)
结果是一个条形图,其中条形图由对应于类别的各种颜色填充.但是,从条到条的颜色排序并不一致.说有粉红色,绿色和蓝色.有些酒吧从下到上呈粉红色,绿色,蓝色,有些则呈绿色,粉红色,蓝色.我没有看到任何明显的模式.
这些订单是如何选择的?我该怎么改变它?至少,我如何让ggplot选择一致的排序?
(x,y和类别)的类别分别是(整数,数字和因子).如果我将类别设为有序因子,则不会更改此行为.
有人知道怎么修这个东西吗?
可重复的例子:
dput(data)
structure(list(mon = c(9L, 10L, 11L, 10L, 8L, 7L, 7L, 11L, 9L,
10L, 12L, 11L, 7L, 12L, 8L, 12L, 9L, 7L, 9L, 10L, 10L, 8L, 12L,
7L, 11L, 10L, 8L, 7L, 11L, 12L, 12L, 9L, 9L, 7L, 7L, 12L, 12L,
9L, 9L, 8L), gclass = structure(c(9L, 1L, 8L, 6L, 4L, 4L, 3L,
6L, 2L, 4L, 1L, 1L, 5L, 7L, 1L, 6L, 8L, 6L, 4L, 7L, 8L, 7L, 9L,
8L, 3L, 5L, 9L, 2L, 7L, 3L, 5L, 5L, 7L, 7L, 9L, 2L, 4L, 1L, 3L,
8L), .Label = c("Down-Down", "Down-Stable", "Down-Up", "Stable-Down",
"Stable-Stable", "Stable-Up", "Up-Down", "Up-Stable", "Up-Up"
), class = c("ordered", "factor")), NG = c(222614.67, 9998.17,
351162.2, 37357.95, 4140.48, 1878.57, 553.86, 40012.25, 766.52,
15733.36, 90676.2, 45000.29, 0, 375699.84, 2424.21, 93094.21,
120547.69, 291.33, 1536.38, 167352.21, 160347.01, 26851.47, 725689.06,
4500.55, 10644.54, 75132.98, 42676.41, 267.65, 392277.64, 33854.26,
384754.67, 7195.93, 88974.2, 20665.79, 7185.69, 45059.64, 60576.96,
3564.53, 1262.39, 9394.15)), .Names = c("mon", "gclass", "NG"
), row.names = c(NA, -40L), class = "data.frame")
ggplot(data,aes(mon,NG,fill=gclass))+geom_bar(stat="identity")
Run Code Online (Sandbox Code Playgroud)
aos*_*ith 49
从ggplot2_2.0.0开始,order
审美不再可用.要获得按填充颜色排序的堆栈图形,您只需按要排序的分组变量对数据集进行排序即可.
我经常使用arrange
从dplyr这一点.在这里,我fill
按照ggplot
调用中的因子对数据集进行排序,而不是创建有序数据集,但两者都可以正常工作.
library(dplyr)
ggplot(arrange(data, gclass), aes(mon, NG, fill = gclass)) +
geom_bar(stat = "identity")
Run Code Online (Sandbox Code Playgroud)
这很容易在基数R中完成,当然,使用order
带有提取括号的经典:
ggplot(data[order(data$gclass), ], aes(mon, NG, fill = gclass)) +
geom_bar(stat = "identity")
Run Code Online (Sandbox Code Playgroud)
ggplot2_2.2.0更新
在ggplot_2.2.0中,填充顺序基于因子级别的顺序.默认顺序将绘制堆栈顶部的第一个级别而不是底部.
如果你想,你可以使用堆栈底部的第一级reverse = TRUE
在position_stack
.请注意,您也可以使用geom_col
快捷方式geom_bar(stat = "identity")
.
ggplot(data, aes(mon, NG, fill = gclass)) +
geom_col(position = position_stack(reverse = TRUE))
Run Code Online (Sandbox Code Playgroud)
Bri*_*ggs 23
您还需要指定order
美学.
ggplot(data,aes(mon,NG,fill=gclass,order=gclass))+
geom_bar(stat="identity")
Run Code Online (Sandbox Code Playgroud)
这可能是也可能不是错误.
要订购,您必须使用levels
参数并告知订购。像这样:
data$gclass
(data$gclass2 <- factor(data$gclass,levels=sample(levels(data$gclass)))) # Look the difference in the factors order
ggplot(data,aes(mon,NG,fill=gclass2))+geom_bar(stat="identity")
Run Code Online (Sandbox Code Playgroud)