代码之家  ›  专栏  ›  技术社区  ›  ulima2_

使用geom_ribbon(ggplot2)绘制具有变化颜色的两个时间序列之间的差异

  •  0
  • ulima2_  · 技术社区  · 7 年前

    使用R:

    library(tidyverse)
    
    data <- tribble(
      ~year, ~exports, ~imports,
      #--|--|----
      2003, 3, 3.6,
      2004, 4, 8.5,
      2005, 7, 7,
      2006, 9, 7,
      2007, 15, 9,
      2008, 17, 12,
      2009, 7, 8,
      2010, 8, 7,
      2011, 8, 8,
      2012, 7, 9,
      2013, 2, 11,
      2014, 9, 13,
      2015, 5, 15
    )
    
    ggplot(data, aes(x = year)) +
      geom_ribbon(aes(ymin = imports, ymax = exports))
    

    这让我明白:

    enter image description here

    这已经在系列之间的差异颜色,但没有告诉我哪一个更高。

    接下来,我尝试了:

    ggplot(data, aes(x = year)) +
      geom_ribbon(aes(ymin = imports, ymax = exports, fill = exports > imports))
    

    enter image description here

    但这里似乎出了什么问题,我不确定是什么问题。

    2 回复  |  直到 7 年前
        1
  •  2
  •   Eric Watt    7 年前

    这就更接近了,尽管在值相等的点没有行的情况下仍然失败。根据您的需要,您可以计算2008年和2009年之间的交叉点,并将其人工添加到您的数据集。

    data$minval <- pmin(data$imports, data$exports)
    
    ggplot(data, aes(x = year)) +
      geom_ribbon(aes(ymin = minval, ymax = exports), fill = "blue") +
      geom_ribbon(aes(ymin = minval, ymax = imports), fill = "red")
    
        2
  •  0
  •   mfalco    3 年前

    stat_difference()

    library(ggh4x)
    
    df <- data.frame(
      x = 1:100,
      y = cumsum(rnorm(100)),
      z = cumsum(rnorm(100))
    )
    
    ggplot(df, aes(x = x)) +
      stat_difference(aes(ymin = y, ymax = z), alpha = 0.3) +
      geom_line(aes(y = y, colour = "min")) +
      geom_line(aes(y = z, colour = "max"))