Icewaffle
Icewaffle

Reputation: 19

ggplot gradient color for geom_line

take the following data and graph

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"))

How do I make the lines a gradient color? The legend displays a gradient color-scheme, but as illustrated the lines don't seem to follow it accurately.

enter image description here

Upvotes: 1

Views: 1003

Answers (1)

Jon Spring
Jon Spring

Reputation: 66425

I don't believe you can vary aesthetics like color within a single instance of a geom in ggplot2 without extra interpolation steps. ggforce::geom_link2 would be a good drop-in replacement to accomplish this:

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

Upvotes: 3

Related Questions