1
votes

Below is the a small dataset which i have tried to reproduce it to my best understanding.As in the attached plot you can observe that i am able to gradient in geom_point() but the same visuals i am trying for geom_line.Note : we are always been provided with data ofTempandvar.Thecat` variable is not given in data set.

df=data.frame(seq=(1:30),Temp =rnorm(30,mean = 34 ,sd=18))
f=summary(df$Temp)
df$cat <- cut(df$Temp,
                   breaks=c(f[1], f[3] ,f[4] ,f[6]),
                   labels=c("low","medium","high"))
f=ggplot(df , aes(x=seq ,y= Temp,colour=cat))+ geom_line()
f

Output of Above Code enter image description here

Required Output enter image description here

Gradient should as per High , Medium & Low using geom_line() function in ggplot2.

2

2 Answers

3
votes

You want to group the lines by cat, but colour them by Temp. For getting a nice gradient, I like the colour scales in the viridis package, but you can play around with scale_colour_gradient instead:

library(viridis)
ggplot(df , aes(x=seq ,y= Temp,colour=Temp, group = cat)) + 
    geom_line(size = 1.2) +
    scale_colour_viridis(option = "A")

Output:

enter image description here

To have a legend for the lines, you can represent cat with something like shape:

ggplot(df , aes(x=seq ,y= Temp,colour=Temp, group = cat, shape = cat)) + 
    geom_point(size = 3) +
    geom_line(size = 1.2) +
    scale_colour_viridis(option = "A")
1
votes

Is this what you want:

a <- data.frame(seq=(1:30),Temp =rnorm(30,mean = 34 ,sd=18))

ggplot(a, aes(x = seq, y = Temp, color = Temp )) + 
  geom_line(size = 0.5)  +
  geom_smooth(aes(color=..y..), size=1.5, method = "loess", se=FALSE) +
  scale_colour_gradient2(low = "green", mid = "yellow" , high = "red", 
                         midpoint=median(a$Temp))