带有堆积条形图的订单图例 - ggplot

时间:2015-10-06 21:00:32

标签: r ggplot2

我正在尝试创建堆叠条形图,一切正常,但由于与fill aestethic相关的图例的排序,很难解释图表。

enter image description here

我希望堆积条符合图例名称的顺序,分别表示每个家庭类别的“住宿”和“汽车费用”。

现在我试了一下,但这似乎不起作用,它涉及重新排列因子列的levels属性。

我的代码

 ggraph$names <- factor(ggraph$names)
  levels(ggraph$names) <- rownames(do.call(rbind, tapply(ggraph[,2], list(ggraph$names), sum, simplify = FALSE)))

  ggplot(ggraph, aes(x = household, y = absChange, fill = names)) + 
    geom_bar(stat = 'identity') + 
    scale_y_continuous(labels = scales::comma) +
    coord_flip()

ggraph对象

> dput(ggraph)
structure(list(names = structure(c(1L, 6L, 4L, 8L, 3L, 1L, 4L, 
6L, 8L, 3L, 1L, 6L, 4L, 8L, 3L, 6L, 8L, 1L, 4L, 9L, 1L, 6L, 4L, 
5L, 2L, 6L, 1L, 8L, 4L, 3L, 1L, 6L, 7L, 4L, 3L), .Label = c("Accomodation", 
"Car expenses", "Groceries", "Household-services", "Interests expenses", 
"Leisure and culture", "Rent (incl garage fee)", "Transportation", 
"Travels, hotel stays"), class = "factor"), absChange = c(18470L, 
16030L, 11540L, 8010L, 6150L, 22740L, 17600L, 14070L, 12990L, 
7520L, 18170L, 17280L, 14720L, 9620L, 5960L, 48340L, 31710L, 
26730L, 16770L, 10520L, 23160L, 17980L, 14030L, 10700L, 10570L, 
16100L, 13930L, 7660L, 7650L, 7320L, 15430L, 13500L, 5900L, 5740L, 
4250L), household = c("all households", "all households", "all households", 
"all households", "all households", "cohabit with child", "cohabit with child", 
"cohabit with child", "cohabit with child", "cohabit with child", 
"cohabit without child", "cohabit without child", "cohabit without child", 
"cohabit without child", "cohabit without child", "other cohabit with child", 
"other cohabit with child", "other cohabit with child", "other cohabit with child", 
"other cohabit with child", "other households", "other households", 
"other households", "other households", "other households", "single parent", 
"single parent", "single parent", "single parent", "single parent", 
"single parent without child", "single parent without child", 
"single parent without child", "single parent without child", 
"single parent without child")), .Names = c("names", "absChange", 
"household"), row.names = c(2L, 3L, 4L, 5L, 6L, 8L, 9L, 10L, 
11L, 12L, 14L, 15L, 16L, 17L, 18L, 20L, 21L, 22L, 23L, 24L, 26L, 
27L, 28L, 29L, 30L, 32L, 33L, 34L, 35L, 36L, 38L, 39L, 40L, 41L, 
42L), class = "data.frame")

1 个答案:

答案 0 :(得分:2)

使用stat = "identity",ggplot按照它们在数据中出现的顺序放置条形图。要与因子级别强加相同的顺序,只需对数据进行排序:

 ggplot(ggraph[order(ggraph$names), ],
        aes(x = household, y = absChange, fill = names)) + 
    geom_bar(stat = 'identity') + 
    scale_y_continuous(labels = scales::comma) +
    coord_flip()

工作得很好。