stat_summary和position_stack给出了不一致的顺序

时间:2016-01-25 21:12:49

标签: r ggplot2

有人能解释下面的不一致行为吗?

示例数据:

structure(list(a11 = c(2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 1L, 
2L, 2L, 1L, 1L, 3L, 2L, 3L, 3L, 1L, 3L, 3L, 3L, 3L, 3L, 1L, 2L, 
1L, 3L, 3L, 3L, 3L, 1L, 3L, 3L, 2L, 5L, 3L, 3L, 3L, 5L, 6L, 3L, 
3L, 3L, 1L, 3L, 2L, 3L, 1L, 3L), variable = structure(c(3L, 2L, 
1L, 2L, 4L, 4L, 3L, 3L, 3L, 4L, 3L, 1L, 4L, 3L, 3L, 1L, 1L, 1L, 
2L, 1L, 3L, 4L, 3L, 1L, 1L, 2L, 2L, 4L, 4L, 4L, 2L, 4L, 1L, 1L, 
2L, 2L, 4L, 2L, 2L, 1L, 4L, 1L, 2L, 1L, 3L, 3L, 1L, 4L, 4L, 3L
), .Label = c("e15_1", "e15_2", "e15_4", "e15_5"), class = "factor"), 
    value = c(0, 85, 0, 0, 5, 10, 50, 20, 100, 0, 0, 0, 40, 50, 
    70, 0, 2, 0, 100, 0, 80, 20, 80, 0, 50, 20, 22, 0, 10, 25, 
    36, 0, 0, 0, 25, 25, 0, 10, 10, 0, 50, 5, 100, 0, 100, 40, 
    80, 0, 50, 50)), .Names = c("a11", "variable", "value"), row.names = c(13984L, 
5521L, 587L, 9204L, 15516L, 18568L, 11912L, 14028L, 14125L, 18348L, 
14085L, 4803L, 17191L, 10902L, 11006L, 4420L, 3996L, 3634L, 5339L, 
3428L, 10279L, 16692L, 13879L, 3778L, 3602L, 8917L, 8283L, 18522L, 
18690L, 18160L, 6897L, 14611L, 1540L, 1973L, 7695L, 9152L, 17636L, 
5909L, 9590L, 420L, 17516L, 617L, 5008L, 4162L, 10631L, 12311L, 
3534L, 17533L, 18206L, 11632L), class = "data.frame")

代码(请注意group中使用aes以及它如何影响中间栏中的订单):

# NOT using group in aes give inconsistent order
p1 <- ggplot(data = tmp) + 
  stat_summary(aes(x = factor(a11), y = value, fill = variable),
               fun.y = mean, geom = "bar", position = "stack")
# Using group in aes gives consistent order
p2 <- ggplot(data = tmp) +
  stat_summary(aes(x = factor(a11), y = value, 
                   fill = variable, group = variable),
               fun.y = mean, geom = "bar", position = "stack")
grid.arrange(p1, p2)

enter image description here

0 个答案:

没有答案