<分区>
我正在绘制由一个变量分割的多个图,在每个图中,颜色代码基于另一个变量。
set.seed(12345)
dates = seq(as.Date("2000-01-01"), as.Date("2016-01-01"), by = 1)
dd = data.table(date = dates, value = rnorm(length(dates)))
dd[, year := lubridate::year(date)]
dd[, c := cut(value, c(-Inf, -3, 3, Inf))]
for (thisyear in 2000:2015) {
ggplot(dd[year == thisyear]) +
geom_ribbon(aes(x = date, ymin = -Inf, ymax = Inf, fill = c), alpha = 0.1)
}
dd[, length(unique(c)), by = year]
year V1
1: 2000 1
2: 2001 2
3: 2002 2
4: 2003 3
5: 2004 3
....
现在,不同地 block 中的颜色将不一致,因为并非每年都有相同长度的独特切割值。更糟糕的是,当一年具有所有 (-Inf,3]
值(当然这不太可能)而另一年具有所有 [3,Inf)
值时,它们都会在两个图中被涂成红色。
我如何指定 (-Inf, 3]
总是取蓝色而 (-3,3]
总是取绿色?