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

时间:2018-04-19 12:51:00

标签: 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)),])

enter image description here

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

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

enter image description here

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

干杯

2 个答案:

答案 0 :(得分: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')

enter image description here

但是,要按照你的要求去做,你可以做一些简单的三角法来投射你的线段

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)

enter image description here

答案 1 :(得分:3)

我认为没有快速解决方案,但您可以这样做:

myDat$AtNode <- factor(myDat$AtNode, levels = unique(paste(myDat[order(myDat$atTime),"AtNode"]))) #Generate factor here so we can use in imputation calculation

impute_rows <- which(myDat$Type == "Track") #Select rows to impute
slope_df <- myDat[impute_rows + c(-1,1), ] #Select rows before and after imputation to calculate slope

line <- lm(as.numeric(AtNode) ~ atTime, data = slope_df) #Get slope of line so we can do the calculations
df <- data.frame(x = myDat[impute_rows, "atTime"], y = myDat[impute_rows, "atTime"]*line$coefficients[["atTime"]] + line$coefficients[["(Intercept)"]], Lane = myDat[impute_rows,"Lane"], Train =  myDat[impute_rows,"Train"])

ggplot(data =myDat, aes(x = atTime, y=AtNode, group = Train, colour = Lane ))+
  geom_path(data = myDat[which(!grepl(pattern = "Track", myDat$Type)),]) + 
  geom_path(data = df, aes(x = x, y = y), size = 2) + 
  scale_y_discrete(drop = FALSE)

enter image description here

这个想法如下:

  • 确定要归档的行:which()
  • 确定要归档slope_df
  • 的行前后的行
  • 使用所需值之前和之后的行来估算您想要计算的线的等式(使用slope_df
  • 根据行df <- data.frame(...)
  • 生成数据

请注意,您还需要scale_y_discrete(drop = FALSE),以便从图中删除Track级别。

相关问题