在下面的示例中,ggplots在堆叠条形图的条形时忽略了我的顺序。请注意,图例中会遵守订单。
预备数据:
plotdf <-
structure(list(.id = structure(c(1L, 1L, 1L, 1L, 1L, 2L, 2L,
2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 5L, 5L, 5L,
5L, 5L, 6L, 6L, 6L, 6L, 6L), .Label = c("C A", "C W", "C R",
"I N D", "I e", "I o"), class = "factor"), grp = structure(c(3L,
1L, 4L, 2L, 5L, 3L, 1L, 4L, 2L, 5L, 3L, 1L, 4L, 2L, 5L, 3L, 1L,
4L, 2L, 5L, 3L, 1L, 4L, 2L, 5L, 3L, 1L, 4L, 2L, 5L), .Label = c("C L",
"F C", "C", "B", "R"), class = "factor"), v = c(0, 0.239181693913566,
0.165857056803677, 0.350750434828833, 0.244210814453923, 0, 0.271188523388472,
0.0962040631815689, 0.272432818496037, 0.360174594933923, 0.0369015572477178,
0.29722089026182, 0.125321399722723, 0.195349629447893, 0.345206523319846,
0, 0.194564544482903, 0.30578720507121, 0.139178183673556, 0.360470066772331,
0.0263516505214496, 0.247452946164384, 0.400260126370759, 0.0579795532895398,
0.267955723653867, 0, 0.369045931493036, 0.372811575779409, 0,
0.258142492727555)), .Names = c(".id", "grp", "v"), row.names = c(NA,
-30L), class = "data.frame")
查看数据 - 有因素
head(plotdf)
## .id grp v
## 1 C A C 0.0000000
## 2 C A C L 0.2391817
## 3 C A B 0.1658571
## 4 C A F C 0.3507504
## 5 C A R 0.2442108
## 6 C W C 0.0000000
str(plotdf)
## 'data.frame': 30 obs. of 3 variables:
## $ .id: Factor w/ 6 levels "C A","C W","C R",..: 1 1 1 1 1 2 2 2 2 2 ...
## $ grp: Factor w/ 5 levels "C L","F C","C",..: 3 1 4 2 5 3 1 4 2 5 ...
## $ v : num 0 0.239 0.166 0.351 0.244 ...
head(plotdf$grp)
## [1] C C L B F C R C
## Levels: C L F C C B R
积
ggplot(plotdf, aes(x=.id, y=v, fill=grp)) + geom_bar(stat="identity")
给了我
答案 0 :(得分:2)
因子级别的顺序指定沿轴和图例中的值的顺序。但出于任何理由,当你堆积条形图时,你还必须设置order=
美学。使用
ggplot(plotdf, aes(x=.id, y=v, fill=grp, order=grp)) + geom_bar(stat="identity")