用R中的一条线连接两个点

时间:2016-06-22 18:22:17

标签: r connect lines points

我在连接具有相同y值的两个点时遇到问题。我的数据集看起来像(我希望格式化正常)

attackerip,min,max
125.88.146.123,2016-03-29 17:38:17.949778,2016-03-30 07:28:47.912983
58.218.205.101,2016-04-05 15:53:20.69986,2016-05-12 17:32:08.583255
183.3.202.195,2016-04-05 15:58:27.862509,2016-04-15 18:15:13.117774
58.218.199.166,2016-04-05 16:09:34.448588,2016-04-24 06:02:12.237922
58.218.204.107,2016-04-05 16:57:17.624509,2016-05-31 00:52:44.007908

到目前为止我的内容如下:

mydata = read.csv("timeline.csv", sep=',')
mydata$min <- strptime(as.character(mydata$min), format='%Y-%m-%d %H:%M:%S')
mydata$max <- strptime(as.character(mydata$max), format='%Y-%m-%d %H:%M:%S')
plot(mydata$min, mydata$attackerip, col="red")
points(mydata$max, mydata$attackerip, col="blue")

结果为:this Plot

现在我想连接具有相同y轴值的点。并且无法获得线条或下线工作。在此先感谢!

编辑:数据输入

dput(mydata)
structure(list(attackerip = structure(c(1L, 5L, 2L, 3L, 4L), .Label = c("125.88.146.123", 
"183.3.202.195", "58.218.199.166", "58.218.204.107", "58.218.205.101"
), class = "factor"), min = structure(1:5, .Label = c("2016-03-29 17:38:17.949778", 
"2016-04-05 15:53:20.69986", "2016-04-05 15:58:27.862509", "2016-04-05 16:09:34.448588", 
"2016-04-05 16:57:17.624509"), class = "factor"), max = structure(c(1L, 
4L, 2L, 3L, 5L), .Label = c("2016-03-30 07:28:47.912983", "2016-04-15 18:15:13.117774", 
"2016-04-24 06:02:12.237922", "2016-05-12 17:32:08.583255", "2016-05-31 00:52:44.007908"
), class = "factor")), .Names = c("attackerip", "min", "max"), class = "data.frame", row.names = c(NA, 
-5L))

最终编辑:

绘制线条不起作用的原因是,min和max的数据类型是时间戳。将这些转换为数值会产生预期的结果。感谢大家的帮助

1 个答案:

答案 0 :(得分:3)

lines函数应该可以正常工作。但是,您需要为共享相同y值的每对(或一组)点调用它。这是一个可重复的例子:

# get sets of observations with the same y value
dupeVals <- unique(y[duplicated(y) | duplicated(y, fromLast=T)])
# put the corresponding indices into a list
dupesList <- lapply(dupeVals, function(i) which(y == i))

# scatter plot
plot(x, y)
# plot the lines using sapply
sapply(dupesList, function(i) lines(x[i], y[i]))

返回

enter image description here

数据

set.seed(1234)
x <- sort(5* runif(30))
y <- sample(25, 30, replace=T)

由于您似乎有两个单独的组,您想要绘制这些线,以下是算法:

  1. 每组,(min和max,我相信)
    • 计算y变量的重复值
    • 将这些重复的标记放入dupesList(可能是dupesListMin和dupesListMax)。
  2. 绘制点
  3. 在每个dupesList上运行一个sapply函数。