R ggplot 为特定值设置颜色

标签 r ggplot2

<分区>

我正在绘制由一个变量分割的多个图,在每个图中,颜色代码基于另一个变量。

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] 总是取绿色?

最佳答案

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

例如:

# 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

关于R ggplot 为特定值设置颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39142596/

相关文章:

r - 如何使用单个预测变量列执行套索回归?

java - 如何让 rJava 在 osx 上使用更新版本的 java?

r - 使用ggplot2为每组添加回归线

r - Tidymodels 包 : Visualising a random forest model using ggplot() to show the most important predictors

按 list() 变量名而不是 R 中的索引重命名

r - 将 3D 数组转换为整齐的数据框?

list - 如何从数据框列表中组合多个箱线图?

r - ggplot : Manually add legends for aesthetics that are not mapped

r - 在组内排序的 Lollipop 图

r - 绘制带有标签的空间坐标