1
我想创建一个堆叠条形图,一切工作,除了它很难解释图表由于与fill
aestethic有关的传说的排序。订购传说与堆积条形图 - ggplot
我想叠置条柱跟随传奇的名字,将先说“住宿”,然后“车费用”每个家庭类别,分别秩序。
现在我做了一个尝试,但这似乎不起作用,它涉及重新排列因子列的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")
只需在绘图前按'names'命令您的数据集。 – aosmith