ggplot更改由x轴值指定的线条颜色

sne*_*ich 3 r ggplot2

代码重现:

myDat <- data.frame(Event = rep(c("Arrival", "Departure"), 3),
                AtNode = c("StationA", "StationA", "Track", "Track", "StationB", "StationB"),
                Lane = c("Lane1", "Lane1", "Lane2", "Lane2", "Lane1", "Lane1"),
                atTime = c(10, 12, 18, 20, 34, 36),
                Type = c("Station", "Station", "Track", "Track", "Station", "Station"),
                Train = 1 )
ggplot(data =myDat, aes(x = atTime, y=factor(AtNode, levels = unique(paste(myDat[order(myDat$atTime),"AtNode"]))), group = Train, colour = Lane ))+
  geom_point(data = myDat)+
  geom_path(data = myDat[which(!grepl(pattern = "Track", myDat$Type)),])
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

现在我需要在橙色线上投射两个绿点(Y ="轨迹"),并将投影点之间的线着色为与点相同的颜色.

预期结果:(没有积分(Y ="追踪"))

在此输入图像描述

提前感谢每一个提示或技巧!

干杯

Fel*_*nga 5

我不认为你的输出是显示你想要的正确方式.你有factors你的y-axis,这意味着它1和3之间.

因此,在那里投射一条线就没有y-axis价值.

对我来说,显示数据的正确方法就是这样

ggplot(data =myDat,
       aes(x = atTime, y=factor(AtNode, levels = unique(paste(myDat[order(myDat$atTime),"AtNode"]))), 
           group = AtNode, colour = Lane ))+
  geom_point()+
  geom_line() +
  labs(y = 'AtNode')
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

但是,要按照您的要求进行操作,您可以使用一些简单的三角函数来投影您的线段

x1 = 1 + tan(asin(2/sqrt(484)))*6 #y projection given x = 18
x2 = 1 + tan(asin(2/sqrt(484)))*8 #y projection given x = 20

foo = data.frame(x = c(18,20), y = c(x1, x2), Lane = "Lane2")

ggplot(data = myDat, aes(x = atTime, y=factor(AtNode, levels = unique(paste(myDat[order(myDat$atTime),"AtNode"]))), group = 1, colour = Lane ))+
  geom_path(data = myDat[which(!grepl(pattern = "Track", myDat$Type)),]) +
  geom_line(data = foo, aes(x = x, y = y, color = Lane), size = 1) +
  scale_y_discrete(drop = FALSE)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述