[英]Use geom_ribbon (ggplot2) to plot difference between two time series with changing colors
我试图通过绘制出口和进口并根据 netexports 是正还是负对两个系列之间的差异进行着色来可视化 netexports(出口 - 进口)。
使用 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))
这让我:
哪个系列之间的差异已经着色,但没有告诉我哪个更高。
接下来我尝试过:
ggplot(data, aes(x = year)) +
geom_ribbon(aes(ymin = imports, ymax = exports, fill = exports > imports))
其中产生:
但这里似乎有问题,我不确定是什么。
尽管这仍然会失败,但是在值相等的地方没有行的情况下仍然失败。 根据您的需求,您可以计算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")
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"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.