2016-08-25 405 views
0

我正在做多个图分割一个变量,并在每个图中,颜色代码基于另一个变量。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]总是绿色?

+0

你是指'(3,Inf)'为绿色的色点吗? –

+0

我无法重现您的错误。在'for'循环中有错误,'thisyear'是什么? – bVa

+0

代码中有几个输入错误:1.'2000年的年份:2015''应该可以读为'2000年的今年':2015年'和2.'dd [year == thisyear]'应该是'dd [year ==今年]' –

回答

1

手动指定要使用的颜色的一种方法是简单地在数据框中创建一个指定要使用的绘图颜色的列。

例如:

# scatter plot 
dd$color <- ifelse(dd$value <= 3, 'blue', 'green') 
ggplot(dd, aes(date, value)) + geom_point(colour=dd$color) 

# ribbon plot 
thisyear <- '2001' 
dd_year <- dd[year == thisyear,] 
ggplot(dd_year, aes(date, group=color, colour=color)) + 
    geom_ribbon(aes(ymin=value - 1, ymax=value + 1, fill=color), alpha=0.5) + 
    scale_fill_manual(values=unique(dd_year$color)) + 
    scale_color_manual(values=unique(dd_year$color)) 

这将导致所有点< = 3被蓝色,和其余的绿色。

不是最有趣的例子也许是因为只有那个被染成绿色这里唯一的数据点,但它应该是这样的:

ggplot2 colored ribbon plot

+0

谢谢。这似乎不适用于'geom_ribbon'的'fill'属性。您可以将'fill'放入'aes'中以获得多种颜色,或者在'aes'之外加入一个常量'fill'。 – jf328

+0

添加了一个条形图示例。 –

+0

'geom_ribbon'代码的工作原理是因为在2000年模拟数据只有1个切割组。它会失败,如果你设置'thisyear = 2001' – jf328

1

您可以创建的颜色传递给一个名为向量scale_fill_manual。这使您可以选择每个组的颜色,并确保每个组的颜色相同。

colors = c("blue", "green", "red") 
names(colors) = levels(dd$c) 

(-Inf,-3] (-3,3] (3, Inf] 
    "blue" "green"  "red" 

现在是同样的情节,但加入了scale_fill_manual

for (thisyear in 2000:2015) { 
    print(ggplot(dd[year == thisyear]) + 
     geom_ribbon(aes(x = date, y = value, ymin = -Inf, ymax = Inf, fill = c), alpha = 0.1) + 
     scale_fill_manual(values = colors)) 
}