我正在做多个图分割一个变量,并在每个图中,颜色代码基于另一个变量。R ggplot设置特定值的颜色
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
....
现在不同地块的颜色会不一致,因为不是每年都有相同长度的独特切割值。更糟糕的是,当一年有所有(-Inf,3]
值(当然不太可能)和另一年有所有[3,Inf)
值时,它们都将在两个地块中被标为红色。
我该如何指定(-Inf, 3]
总是蓝色和(-3,3]
总是绿色?
你是指'(3,Inf)'为绿色的色点吗? –
我无法重现您的错误。在'for'循环中有错误,'thisyear'是什么? – bVa
代码中有几个输入错误:1.'2000年的年份:2015''应该可以读为'2000年的今年':2015年'和2.'dd [year == thisyear]'应该是'dd [year ==今年]' –