geom_line 的 ggplot 渐变颜色

时间:2021-06-20 00:59:26

标签: r ggplot2

取以下数据和图表

df <- data.frame(ID = c(1, 1, 2, 2, 3, 3),
                 cond = c(2, 2, 2, 2, 2, 2),
                 Time = c(1,2,1,2,1,2),
                 State  = c("Empty", "Empty", "Empty", "Full", "Full", "Empty"),
                 eye = c(2, -3, -2, 1, 0, -2),
                 combination = c(1, 1,2, 2, 3, 3))
ggplot(df, aes(x = Time, y = eye)) +
  geom_point(aes(shape=State), size = 3.5) +
  scale_shape_manual(values=c(13,15)) +  
  geom_line(aes(group=ID, color = Time), size = 5) +
    
  theme(legend.title=element_blank(),
        axis.title.x=element_text(size = 12),
        axis.title.y=element_text(size = 12),
        plot.title = element_text(hjust = 0.5, size = 15),
        axis.text.x= element_text(color = "black"),
        axis.text.y= element_text(color = "black"),
        axis.line = element_line(colour = "black"),
        plot.background = element_rect(fill = "white"),
        panel.background = element_rect(fill = "white"))

如何使线条成为渐变色?图例显示渐变配色方案,但如图所示,线条似乎没有准确地遵循它。

enter image description here

1 个答案:

答案 0 :(得分:2)

我不相信您可以在 ggplot2 中的单个 geom 实例中改变美学,例如颜色,而无需额外的插值步骤。 ggforce::geom_link2 将是一个很好的替代品来完成这个:

ggplot(df, aes(x = Time, y = eye)) +
  ggforce::geom_link2(aes(group=ID, color = Time), size = 5, n = 500, lineend = "round") +
  geom_point(aes(shape=State), size = 3.5) +
  scale_shape_manual(values=c(13,15)) + ....

enter image description here