【问题标题】:stacking order in ggplot2 after order aesthetic has been removed删除订单美学后,ggplot2中的堆叠顺序
【发布时间】: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 可以通过在绘图前对数据框进行排序来更改堆叠顺序。这似乎是一种非常奇怪的行为,它会导致条形之间的堆叠顺序不同。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    您从哪里获得 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"))
    

    产生情节:

    此外,aes_group_order 的文档仍然说这种美学“也可用于更改散点图的绘图顺序”(http://docs.ggplot2.org/current/aes_group_order.html),运行?order 也不会显示任何关于弃用的标志。我正在运行 1.01,根据 github,这似乎是最新版本。

    【讨论】:

      【解决方案2】:

      我不知道为什么,但堆栈按幻影值顺序排列了国家。

      这项工作:

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

      【讨论】:

      • 要使图例顺序与绘图顺序相匹配,请参阅guide_legendreverse 参数。
      猜你喜欢
      • 1970-01-01
      • 2021-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多