2015-11-04 77 views
2

ggplot2的最新版本已删除订单审美,以前可用于指定条形图的堆叠顺序。在此示例中,第一个图表将图例按照> b> c排序。订单审美被删除后ggplot2中的堆叠顺序

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

enter image description here

我然后重新排序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不见了?

enter image description here

更新:

order审美的折旧是在消息公布ggplot2 version 1.10aes_group_order的文档涉及版本0.9.3.1。

正如以下答案之一所述,堆叠顺序似乎取决于它在数据框中的显示位置。因此,在绘图之前可以通过排序数据帧来改变堆叠顺序。这似乎是非常奇怪的行为,它会导致条之间的堆叠顺序不同。

回答

0

你从哪里得到ggplot2的最新版本去除订单审美的信息?据我所知,order审美仍然活着,踢。我

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, order = country)) + 
    geom_bar(stat = "identity") + 
    scale_x_date(labels = date_format("%Y-%m-%d")) 

下面的代码产生的情节:

Plot showing reordered bar chart

此外,aes_group_order文件还称这种审美“也可以用来改变散点图的情节令”(http://docs.ggplot2.org/current/aes_group_order.html ),也不会运行?order调出有关弃用的任何标志。我正在运行1.01,这似乎是根据github的最新版本。

0

我不知道为什么,但堆栈拿着国家的价值幻影的顺序。

这项工作:

temp <- subset(df, date == max(df$date)) 
level_order <- temp[order(temp$value, decreasing = TRUE), "country"] 
df <- df[c(3, 1, 2, 6, 4, 5), ] 
df$country <- factor(df$country, levels = level_order, labels = level_order) 

ggplot(df, aes(x = date, y = value)) + 
    geom_bar(stat = "identity", aes(fill = country)) + 
    scale_x_date(labels = date_format("%Y-%m-%d")) 

enter image description here

+1

为了得到传说为了配合剧情顺序,请参阅guide_legend'的'了'reverse'说法。 – aosmith