【发布时间】:2016-02-05 06:10:54
【问题描述】:
最新版本的 ggplot2 删除了顺序美学,以前可以用来指定条形图的堆叠顺序。在此示例中,第一个图表的图例顺序为 a > b > c。
df <- data.frame(date = rep(seq(as.Date("2015-11-02"),
as.Date("2015-11-03"), 1), each = 3),
country = rep(c("a", "b", "c"), 2),
value = c(10, 2, 4, 3, 2, 5), stringsAsFactors = FALSE)
ggplot(df, aes(x = date, y = value, fill = country)) +
geom_bar(stat = "identity") +
scale_x_date(labels = date_format("%Y-%m-%d"))
然后我将 country 变量重新排序为根据最后日期的顺序(即 c > a > b)。我现在希望 c 在堆栈和图例中都位于底部。但是,只有颜色和图例会切换,而不是堆叠顺序。
temp <- subset(df, date == max(df$date))
level_order <- temp[order(temp$value, decreasing = TRUE), "country"]
df$country <- factor(df$country, levels = level_order)
ggplot(df, aes(x = date, y = value, fill = country)) +
geom_bar(stat = "identity") +
scale_x_date(labels = date_format("%Y-%m-%d"))
在早期版本的 ggplot2 中,可以使用 aes(order = country) 解决此问题。 order 没了怎么办?
更新:
order 美学的弃用在 ggplot2 version 1.10 的新闻中宣布。 aes_group_order 的文档是指版本 0.9.3.1。
正如以下答案之一所讨论的,堆叠顺序似乎取决于它在数据框中出现的位置。因此,on 可以通过在绘图前对数据框进行排序来更改堆叠顺序。这似乎是一种非常奇怪的行为,它会导致条形之间的堆叠顺序不同。
【问题讨论】: