使用ggplot_line()

时间:2017-06-15 04:28:50

标签: r ggplot2 plotly

下面是一个小数据集,我试图将其重现为我最好的理解。如附图所示,您可以观察到我能够在geom_point()中进行渐变,但我正在为geom_line尝试相同的视觉效果。{ {1}}数据集中未给出临时Note : we are always been provided with data of var and cat`变量。

.The

以上代码的输出 enter image description here

必需输出 enter image description here

渐变应符合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 High&amp;在{ggplot2中使用geom_line()函数Medium

2 个答案:

答案 0 :(得分:1)

这就是你想要的:

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

答案 1 :(得分:1)

您希望按cat对行进行分组,但要按Temp对其进行着色。为了获得漂亮的渐变,我喜欢viridis包中的色阶,但您可以改为使用scale_colour_gradient

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

输出:

enter image description here

要获得线条的图例,您可以使用类似的内容来表示cat 形状:

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")
相关问题