简体   繁体   中英

Use geom_ribbon (ggplot2) to plot difference between two time series with changing colors

I'm trying to visualize netexports (exports - imports) by plotting both exports and imports and coloring the difference between the two series depending on whether netexports are positive or negative.

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

This gets me:

在此处输入图片说明

Which already colors in the differences between the series, but doesn't tell me which one is higher.

Next I've tried:

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

Which yields:

在此处输入图片说明

But there seems to be something wrong here and I'm not sure what it is.

This gets closer, though it still fails where you don't have a row at the point where the values are equal. Depending on your needs, you could calculate the point between 2008 and 2009 where they cross, and artificially add it to your dataset.

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

There is the stat_difference() that makes a ribbon that is filled depending on whether the max is higher than min:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM