ggplot:在x轴的一个特定点处通过它们的值指定线的颜色

时间:2016-04-05 09:29:34

标签: r ggplot2

我有一条颜色从黑到绿的线条图。但是,我想在x轴上的“Value2”处逐渐将它们的y值着色。 “Value2”中y值最高的行应为绿色,“Value2”中y值最低的行应为黑色。

如何根据x轴特定点的y值为线条指定颜色?

我的代码:

library(ggplot2)

x <- structure(list(ID = c("1998-06-05_area2", "1999-07-11_area2", 
"1998-05-13_area1", "1998-05-20_area1", "1998-06-05_area2", "1999-07-11_area2", 
"1998-05-13_area1", "1998-05-20_area1", "1998-06-05_area2", "1999-07-11_area2", 
"1998-05-13_area1", "1998-05-20_area1"), variable = structure(c(1L, 
1L, 1L, 1L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L), .Label = c("Value1", 
"Value2", "Value3"), class = "factor"), value = c(322, 280, 210, 
416, 384, 252, 329, 601, 83, 66, 100, 147)), .Names = c("ID", 
"variable", "value"), na.action = structure(c(1L, 2L, 3L, 4L, 
13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 25L, 26L, 27L, 28L), .Names = c("1", 
"2", "3", "4", "13", "14", "15", "16", "17", "18", "19", "20", 
"25", "26", "27", "28"), class = "omit"), row.names = c(5L, 6L, 
7L, 8L, 9L, 10L, 11L, 12L, 21L, 22L, 23L, 24L), class = "data.frame")

pal <- colorRampPalette(c("black","green"))
colorlist <- pal(length(unique(x$ID)))

ggplot(data = x , aes(x = variable, y = value, color = ID))  +
  geom_line(aes(group =ID),size=1) + geom_point(size = 2) +
  scale_colour_manual(values=colorlist)

1 个答案:

答案 0 :(得分:3)

我们可以使用dplyr在数据中创建一个额外的列以进行相应的颜色映射,然后将其输入ggplot()调用以生成绘图。

library(dplyr)
library(ggplot2)
x %>% group_by(ID) %>%
  mutate(col = value[variable == "Value2"]) %>% # Add column to map colours
    ggplot(aes(x = variable, y = value, color = factor(col)))  +
    geom_line(aes(group =ID),size=1) + geom_point(size = 2) +
    scale_colour_manual(values=colorlist)

enter image description here