2015-10-06 62 views
1

我想創建一個堆疊條形圖,一切工作,除了它很難解釋圖表由於與fill aestethic有關的傳說的排序。訂購傳說與堆積條形圖 - ggplot

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") 
+2

只需在繪圖前按'names'命令您的數據集。 – aosmith

回答

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() 

工作得很好。